Search code examples
jsonpathjson-path-expression

How to filter elements by node key in JSONPath?


What I want

Apply a JSONPath to given json response, to match specific elements by comparing their children's node keys with a value.

Input

{
    "data":  {
        "ticket": {
            "1": "foo",
            "2": "bar",
            "3": "baz"
        }
    }
}

Output (expected)

            "3": "baz"

Case description

I want to apply a JSONPath expression, to filter ticket elements with ticket key greater than "2", so in this case it should match only the 3rd "baz" ticket.

ticket keys are only integer numbers in my data

Code area

This matches all node keys aka ticket keys

$.data.ticket.*~

This is a basic example of filtering

$..book[?(@.price<10)]  // -> filter all books cheaper than 10

I am trying somehow to combine them in order to achieve the desired result

Where I test it

https://jsonpath.com/

References

https://goessner.net/articles/JsonPath/


Solution

  • It is possible with jsonpath-plus. The site https://jsonpath.com/ uses jsonpath-plus library internally.

    It has some convenient additions or elaborations not provided in the original spec of jsonpath.

    Use the @property to compare the value of the key.

    $.data.ticket[?(@property > 2)]
    

    enter image description here