Search code examples
jsonjsonpathjson-path-expression

json-path: first element from an array fiilter result


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.


Solution

  • 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));