Functions min(), max() or sum() with jsonpath

送分小仙女□ 提交于 2019-12-12 19:14:25

问题


According to JsonPath on GitHub it shall be possible to access max(), min() or the sum() of an array but I dont know how. With this exampledata:

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

I would expect it to work like

$..book.length

so im trying

$..price.sum

but that didn't do the job.

Can someone help me?


回答1:


From the docs:

Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression

Given this statement, you might expect the example JSON you supplied above to work with an expression such as $.store..price.max() but this expression does not work, instead it throws an error:

Aggregation function attempted to calculate value using empty array

You can read more about that in this JsonPath issue on GitHub.

Meanwhile, here's an example which does work.

Given the following JSON:

{
  "price": [
      1.0,
      2.0
  ]
}

The JsonPath functions work as follows:

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

The above have been verified using the online evaluator.



来源:https://stackoverflow.com/questions/52817156/functions-min-max-or-sum-with-jsonpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!