Tree55Topz
Tree55Topz

Reputation: 1142

Looping through JObject nested array

I can not figure out exactly how to did through this JObject in order to retrieve the id property under runs.

I have this following code which will successfully give me the id property that is under entries, but how can I nest this again to go into the runs sections and get those ID's?

JSON:

{
  "id": 168,
  "name": "section 1",
  "entries": [
    {
      "id": "908-9876-908",
      "suite_id": 15,
      "name": "List 1",
      "runs": [
        {
          "id": 169,
          "suite_id": 15
        }
      ]
    },
    {
      "id": "998-4344-439",
      "suite_id": 16,
      "name": "List 2",
      "runs": [
        {
          "id": 170,
          "suite_id": 16
        }
      ]
    }
  ]
}

C# Code:

JObject obj = JsonConvert.DeserializeObject<JObject>(response);

foreach (JObject id in obj["entries"])
{
    string returnable = (string)id["id"];
    Console.WriteLine(returnable);
}

I have tried looking at ["entries"]["runs"] but that also was not working.

The print out of this is:

908-9876-908
998-4344-439

What I would like is

169
170

Upvotes: 0

Views: 3390

Answers (2)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

You can achieve it using the following code

var jsonObject = JObject.Parse(json);

foreach (var entry in jsonObject["entries"])
{
    foreach (var run in entry["runs"])
    {
        string returnable = (string)run["id"];
        Console.WriteLine(returnable);
    }               
}

You would like to see

169
170

They are an id values from runs array, therefore you should enumerate them in the inner loop. You've also missed a comma after "name": "section 1"

Upvotes: 4

dbc
dbc

Reputation: 116785

You can use SelectTokens() to query for nested data inside a JToken hierarchy. It provides support for JSONPath queries including wildcards [*] for arrays:

var ids = obj.SelectTokens("entries[*].runs[*].id").Select(i => (long)i).ToList();  

See: Querying JSON with complex JSON Path.

Demo fiddle here.

Upvotes: 1

Related Questions