0

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

2 Answers 2

4

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Oh man this worked perfectly - I tried something just like this and was getting errors, I must have just been a little off. Thank you so much, hope this post helps someone else
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.