Get specific object from JSONPath array result aft

2020-04-19 05:00发布

问题:

In JSONPath 0.9.1 the following Json path was valid:

http://jsonpath.herokuapp.com/?path=$.store.book[?(@.author==%27Nigel%20Rees%27)][0]

returning

{
  "category" : "reference",
  "author" : "Nigel Rees",
  "title" : "Sayings of the Century",
  "price" : 8.95
}

I've upgraded to the latest one (2.3) and the query now returns empty array.

Is this a bug or the way to retrieve an element from the resulting array has changed?

回答1:

Given this document:

{
    "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
}

Using JsonPath 2.3.0, the following code returns a JSONArray (rather than an Object[]):

JsonPath.parse(JSON).read("$.store.book[?(@.author==\"Nigel Rees\")]");

So, the following code ...

JSONArray read = JsonPath.parse(JSON).read("$.store.book[?(@.author==\"Nigel Rees\")]");
System.out.println(read.get(0));

... will print:

{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}