JsonPath with Newtonsoft.JSON

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

my JSON object:

"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 all values ​​from Newtonsoft.JSON where the language is "de". My current approach:

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

      

Can anyone help me?

respectfully

+3


source to share


2 answers


You are very close. You need to account for the external array value

typeOfHair.value[]

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:



["TrockenesHaar","JedenHaartyp"]

      

Example fiddle .

+3


source


I know the OP set the JSONPath explicitly, but for completeness, below is how to achieve the same result with LINQ to JSON:

var values = jObject["typeOfHair"]["value"]
    .SelectMany(v => v["values"])
    .Where(v => (string)v["language"] == "de")
    .Select(v => (string)v["value"])
    .ToList();

      



Demo: https://dotnetfiddle.net/1S4sT4

0


source







All Articles