在java中使用JsonPath查找json字段的最大值

在java中使用JsonPath查找json字段的最大值,java,json,jsonpath,Java,Json,Jsonpath,我浏览了这份文件: 但我不知道如何找到特定字段的最大值。 在给定的json中,如果我想知道最昂贵的书的价格,该怎么办 以下是json: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "pri

我浏览了这份文件:

但我不知道如何找到特定字段的最大值。 在给定的json中,如果我想知道最昂贵的书的价格,该怎么办

以下是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": 29.95
        }
    },
    "expensive": 10
 }

要找到一本书的最高价格,jsonpath表达式(在java中)是什么。这里的答案应该是22.99。

您可以尝试以下方法:

var myArray = JSON.parse(jsonAsString)["book"];
var max = myArray .reduce(function(a, b) {
   return Math.max(a, b.price);
}, 0);

假设jPathStrB是上述json的StringBuilder。(编辑:我现在意识到您使用的是另一个jayway jsonpath库,而不是基于groovy的库。下面的答案使用了rest assured附带的jsonpath,它依赖于groovy“max()”方法。)


我参加这次聚会已经很晚了,但从2.4.0版开始,JsonPath不支持您期望的行为

来自维护者:

您正在尝试将函数max()应用于求值结果。事情不是这样的。该函数将应用于与路径匹配的每个对象

为了获得答案,您需要手动将每个路径添加到数组中:

$.max($.store.book[0].price, $.store.book[1].price, $.store.book[2].price, $.store.book[3].price)
我认为,根据自述文件中的文档,大多数人都希望如果以前的作品成功,那么这也应该:

$.max($.store.book[*].price)
但它却抛出了一个错误:

Aggregation function attempted to calculate value using empty array
我们的讨论可以追溯到2016年。 还有一个旧的拉取请求: 这似乎已经在它上面了,包括在maven central上的何处可以找到它。

最近,有一个合并公司声称解决了这个问题。
Aggregation function attempted to calculate value using empty array