Home > Software engineering >  Json group array with a node value
Json group array with a node value

Time:05-26

I have a json with below structure.

{
  "root": {
    "students": [
      {
        "student": {
          "Id": "1",
          "Name": "abc"
        },
        "Type": "Update",
        "Time": "20220520050003Z"
      },
      {
        "student": {
          "Id": "2",
          "Name": "def"
        },
        "Type": "Update",
        "Time": "20220520050009Z"
      },
      {
        "student": {
          "Id": "3",
          "Name": "ghi"
        },
        "Type": "Create",
        "Time": "20220520050021Z"
      },
      {
        "student": {
          "Id": "1",
          "Name": "abc"
        },
        "Type": "Create",
        "Time": "20220520050024Z"
      }
    ]
  }
}

I want to read the students json array and group them which has same Id under student object

For example Id 1 has two entries

{
        "student": {
          "Id": "1",
          "Name": "abc"
        },
        "Type": "Update",
        "Time": "20220520050003Z"
}

and

{
        "student": {
          "Id": "1",
          "Name": "abc"
        },
        "Type": "Create",
        "eventTime": "20220520050024Z"
}

So I want to group them based on same id and get a list of objects which has record for each unique Id.

I tried with newtonsoft linq , but not able to group them with Id value. I want to know how i can group them

JObject obj = JObject.Parse(jsonasstring);
JObject objRoot = (JObject)obj.SelectToken("root");
var studentsList = from students in objRoot["students"]
                      select students["student"];

CodePudding user response:

Select all objects in the students JSON array, then use Linq's GroupBy to bucket them by the student.Id property.

var studentsGroupedById = JObject.Parse(jsonasstring)
    .SelectTokens("$.root.students[*]")
    .GroupBy(x => x["student"]["Id"]);

In each group, Key is the student.Id property, and you can enumerate through all the entries in the group (the inner foreach loop).

enter image description here

  • Related