Home > front end >  JSON.NET only return nodes that contain a specific child node
JSON.NET only return nodes that contain a specific child node

Time:02-05

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"
            }
        ]
    }
]

CodePudding user response:

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();

CodePudding user response:

the simpliest way is

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