Michael Hollander
Michael Hollander

Reputation: 11

JSON.NET only return nodes that contain a specific child node

When doing a SelectToken in JSON.NET, is there a way I could return a list of JTokens of elements that contain a certain child element? For example, is there a SelectToken that would only return the nodes where the "status" child exists from my sample JSON below?

"Fruits": [
    {
        "id": "1",
        "value": "apple"
    },
    {
        "id": "2",
        "value": "banana",
        "status": [
            {
                "fresh": "yes",
                "peeled": "no"
            }
        ]
    },
    {
        "id": "3",
        "value": "orange",
        "status": [
            {
                "fresh": "yes",
                "peeled": "yes"
            }
        ]
    }
]

Upvotes: 0

Views: 879

Answers (2)

Serge
Serge

Reputation: 43890

the simpliest way is

var fruitsWithStatus=JObject.Parse(json)["Fruits"].Where(f => f["status"]!=null ).ToList();

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 142288

You can use LINQ to JSON API for such task (assuming Fruits is json property on root json object) :

var jObject = JObject.Parse(json_string);
var list = jObject
    .Descendants()
    .OfType<JObject>()
    .Where(jp => jp.Children<JProperty>().Any(token => token.Name == "status"))
    .ToList();

Or using json path:

var list = jObject.SelectTokens("$.Fruits[?(@.status)]").ToList();

Upvotes: 1

Related Questions