Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch multiple values from JSON array with nested object using JSONPATH?

Tags:

json

jsonpath

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.

like image 439
BCJ Avatar asked Sep 07 '25 22:09

BCJ


2 Answers

with JSONPath-Plus you can use the below query

store.book[0].[title,author,year]

Tested here: https://jsonpath.com/

enter image description here

like image 169
Akshay G Avatar answered Sep 10 '25 10:09

Akshay G


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).

like image 28
wp78de Avatar answered Sep 10 '25 12:09

wp78de