I need to fetch multiple values from a JSON array with nested objects (example JSON below) using JSONPATH.
{
"store": {
"name": "ABC Co",
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95,
"edition": {
"year": 1990,
"published_by": "MacMillan"
}
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99,
"edition": {
"year": 1980,
"published_by": "MacMillan"
}
}
]
}
}
When I tried, this works good upto parent object level.
store.book[0].[title,author]
["Sayings of the Century", "Nigel Rees"]
Now I want to fetch child object values (edition.year) too. Something like this:
["Sayings of the Century", "Nigel Rees", 1990]
But the below expression is not working:
store.book[0].[title,author,edition.year]
Can anyone help on this? Thanks.
with JSONPath-Plus you can use the below query
store.book[0].[title,author,year]
Tested here: https://jsonpath.com/
The feature at play here is called union. While there is no binding standard on how to implement unions in a JsonPath library, most only allow for union'ing two properties. C. Burgmer compiled an overview of different JsonPath implementations and their behavior, and there is no feature to union more than two (flat) properties listed. So, this is implementation-specific, and most don't support it.
The next best thing I found is union'ing three properties on the same level using Goessner's JsonPath or JsonPath-Plus (both JavaScript):
$.store.book[0].[title,author,edition]
Which results in
[
"Sayings of the Century",
"Nigel Rees",
{
"year": 1990,
"published_by": "MacMillan"
}
]
You can try it online here or here (Goessner tab).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With