Reputation: 1119
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
Upvotes: 5
Views: 7150
Reputation: 9650
I know the OP specified JSONPath explicitly but for the sake of completeness below is how to achieve the same 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
Upvotes: -2
Reputation: 116785
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.
Upvotes: 7