Easier way to find deep child elements in a deeply nested JSON in Newtonsoft?

I have a very deeply nested JSON file that is like this:

{
   // many levels of nesting, from 10 to 50
   items: [{
       video: { // some data }
   }, {
       video: { // some data }
   }]
}

I know I can use json.SelectTokens("long path here") to select those video elements. But it's not efficient and developer-friendly when you want to work with hugely nested JSON files all over the places.

Do we have an alternative easier path like CSS-selectors for this?

Upvotes: 2

Views: 1664

Answers (2)

Reza Kajbaf
Reza Kajbaf

Reputation: 517

An easier way in my opinion is to use the SelectToken/SelectTokens which use JSONPath to look deep into an object.

var video = o.SelectToken("$.items[?(@.id == 1)]");

Read this for more information:

https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm

Upvotes: 0

prd
prd

Reputation: 2321

You can search for nested objects using LINQ and the Descendants method.

const string json = @"{
    items: [{
        video: { id: 1, title: 'Video 1' }
    }, {
        video: { id: 2, title: 'Video 2' }
    }]
}";

var videos = JObject.Parse(json)
    .Descendants()
    .Where(x => x is JObject && x["id"] != null)
    .ToList();

var video = videos.Find(x => (int) x["id"] == 1);

When executing the code from above, the video variable contains the following:

{ "id": 1, "title": "Video 1" }

Upvotes: 1

Related Questions