Search code examples
javajsonpathrest-assured-jsonpathjson-path-expression

How to print jsonpath for json object


I am looking for java API which prints jsonpath for all fields in json object. My 1st part of requirement is like, for given json object (or string) -

{
"store": {
    "book": [
        {
            "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "price": 8.95
        },
        {
            "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 12.99
        }
}

it should print all properties in key-value manner where key is jsonpath of the field.

the output should look something like below -

$.store.book[0].category=reference
$.store.book[0].author=Nigel Rees
$.store.book[0].title=Sayings of the Century
$.store.book[0].price=8.95
$.store.book[1].category=fiction
$.store.book[1].author=Evelyn Waugh
$.store.book[1].title=Sword of Honour
$.store.book[1].price=12.99

and so on. this will be used to match values from another json object (my 2nd requirement).

I found an API https://github.com/json-path/JsonPath which is somewhat fits to 2nd part of my requirement but is does not have any utility method or a method to get JsonPath for a object or field.

Is there any java api or method in jsonpath where I can get jsonpath for given field in json object?


Solution

  • Have you tried to use the gson library, take a look at com.google.gson.stream.JsonReader.getPath() I think this will get you on the right direction.