使用 jsonpath 函数 min()、max() 或 sum()

sma*_*ica 3 java jsonpath

根据GitHub 上的 JsonPath,应该可以访问数组的 max()、min() 或 sum(),但我不知道如何访问。使用此示例数据:

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

我希望它像

$..book.length
Run Code Online (Sandbox Code Playgroud)

所以我在努力

$..price.sum
Run Code Online (Sandbox Code Playgroud)

但这并没有起到作用。

有人能帮我吗?

gly*_*ing 6

从文档:

函数可以在路径的尾端调用——函数的输入是路径表达式的输出

鉴于此语句,您可能希望上面提供的示例 JSON 与表达式一起使用,$.store..price.max()但此表达式不起作用,而是抛出错误:

聚合函数尝试使用空数组计算值

您可以在 GitHub 上的这个JsonPath 问题中阅读更多相关信息。

同时,这是一个有效的例子。

给定以下 JSON:

{
  "price": [
      1.0,
      2.0
  ]
}
Run Code Online (Sandbox Code Playgroud)

JsonPath 函数的工作方式如下:

  • $..price.min() 返回 [1.0]
  • $..price.max() 返回 [2.0]
  • $..price.sum() 返回 [3.0]

以上已使用在线评估器进行了验证。