Search code examples
jsonjson.netjsonpath

JsonPath with Newtonsoft.JSON


I tried for nearly an hour different approaches, but I don't get it ;(

my JSON object is this:

"typeOfHair": {
    "value": [
        {
            "code": "Dry Hair",
            "values": [
                {
                    "value": "DryHair",
                    "language": "en"
                },
                {
                    "value": "TrockenesHaar",
                    "language": "de"
                }
            ]
        },
        {
            "code": "Any Type of Hair",
            "values": [
                {
                    "value": "AnyTypeOfHair",
                    "language": "en"
                },
                {
                    "value": "JedenHaartyp",
                    "language": "de"
                }
            ]
        }
    ]
}

And my task is to get with Newtonsoft.JSON all values where the language is "de". My current approach is:

JsonObject.SelectTokens("typeOfHair.value.values[?(@.language == 'de')].value").ToList()

Can someone help me with this?

Kind regards


Solution

  • You're very close. You need to account for the outer value array typeOfHair.value[] by using the JsonPATH wildcard operator [*]:

    var values = JsonObject.SelectTokens("typeOfHair.value[*].values[?(@.language == 'de')].value")
        // Convert from JValue to string
        .Select(v => (string)v)
        // Save in a list
        .ToList();
    

    And, the result is:

    ["TrockenesHaar","JedenHaartyp"]
    

    Sample fiddle.