Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jsonpath to get parent node

Tags:

jsonpath

Using node JSONPath, how can I get the parent node name from child node value

{
  "store": {
    "book": [
      {
        "id":"1",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "id":"2",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }
    ]
  }
}

I use this expression to identify the child node based on value, I want to use this child node to find the parent node

$.[?(@.id =="1")]
like image 679
Aumer Hadi Avatar asked Jan 04 '23 15:01

Aumer Hadi


2 Answers

You do not specify which implementation of JSON Path, but with both Gatling (Scala) and JayWay (Java) you can use nested filters to filter by children while returning the parent, grandparent or whatever. Here is a sample:

With this JSON:

{
  "a": {
    "b": {
        "c": {
            "d": {
                "e": "foo"
            }
        },
        "something": "bar"
    }
  }
}

And this path:

$.a.b[?(@.c[?(@.d[?(@.e == "foo")])])].something

Returns:

[ "bar" ]

I am able to retrieve b by using expressions to get to lower nodes as the filter.

Some other implementations error out on these expressions.

like image 71
Jayson Minard Avatar answered Jan 07 '23 04:01

Jayson Minard


With JayWay it works but the query provided by Jayson is wrong, because if you change the value to "foo2" it will still return "bar".

This can be tested on http://jsonpath.herokuapp.com/.

Query:

$.a.b[?(@.c.d.e=="foo")].something

Returns:

["bar"]

Query:

$.a.b[?(@.c.d.e=="foo2")].something

Returns:

[]
like image 26
Antonio Severien Avatar answered Jan 07 '23 06:01

Antonio Severien