应用谓词后,从JSONPath数组结果中获取特定对象

时间:2017-11-30 11:12:36

标签: arrays jsonpath

在JSONPath 0.9.1中,以下Json路径有效:

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

返回

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

我已升级到最新版本(2.3),现在查询返回空数组。

这是一个错误还是从结果数组中检索元素的方式发生了变化?

1 个答案:

答案 0 :(得分:1)

鉴于此文件:

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

使用JsonPath 2.3.0,以下代码返回JSONArray(而不是Object[]):

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

所以,以下代码......

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

...将打印:

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