0

I'm new to json-path, but I have often used xpath. My problem is to extract, with json-path, the nth element of an array resulting from a previus filter. For example with the following json

{
    "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
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

I want to match the first book with category "fiction"

I tried with

$..book[?(@.category=='fiction')][0]

but seems it does not work with any of the online evaluation tools.

Where is the error?

Thanks in advance.

Christian W.
  • 2,532
  • 1
  • 19
  • 31
fede.dev
  • 3
  • 1
  • 2

1 Answers1

0

You can try mapping the books array in a list that meets your condition and get the nth element from there. Like:

List<Map<String, Object>> bookList = JsonPath.parse(your_json).read("$..book[?(@.category=='fiction')]", List.class);
System.out.println("Printing the nth book = "+expensiveBooks.get(n));
Yassir Arafat Roni
  • 282
  • 1
  • 2
  • 15
  • 2
    Yes, sorry, I did not specify. Programmatically I had solved in way similar to the one suggested by you. I was just curious to find out if there was a json-path syntax able to extract the value directly. Thanks – fede.dev Aug 09 '18 at 13:13
  • 1
    Actually till now json-path syntax doesn't support such query. – Yassir Arafat Roni Aug 10 '18 at 08:30