从JSONPath中的过滤器表达式中选择第N个项目

Roy*_*_ro 6 json jsonpath

我一直在尝试使用JSONPath过滤JSON中的特定元素,然后仅选择返回结果数组中的第一项。

我的baisc JSONPath看起来像这样:

$.store.book[?(@.category==fiction)].price
Run Code Online (Sandbox Code Playgroud)

我想这样添加此[0]过滤器:

$.store.book[?(@.category==fiction)][0].price
Run Code Online (Sandbox Code Playgroud)

但是它不返回结果,或者如果我[0]在最后一个“价格”之后放置,则会出现此错误:

过滤器:[0] ['price']仅可应用于数组

我一直在搜索,并且在应用过滤器后找不到正确的语法来提取数组中的第一个元素,就像在xpath中一样。

这是我正在使用的基本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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 1

目前唯一的解决办法是:

List<Double> prices = JsonPath
   .parse(json)
   .read("$.store.book[?(@.category == 'fiction')].price");

Double firstPrice = prices.isEmpty() ? null : prices.get(0);
Run Code Online (Sandbox Code Playgroud)