根据JsonPath on GitHub,应该可以访问数组的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
}
}
}
我希望它像
$..book.length
我正在尝试
$..price.sum
但是那没做。
有人可以帮我吗?
答案 0 :(得分:2)
您可以尝试以下操作:-
用于计算SUM
$.sum($.store.book[0].price,$.store.book[1].price,$.store.book[2].price,$.store.book[3].price)
最小和最大
$.max($.store.book[0].price,$.store.book[1].price,$.store.book[2].price,$.store.book[3].price)
$.min($.store.book[0].price,$.store.book[1].price,$.store.book[2].price,$.store.book[3].price)
使用此示例数据:
{
"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
}
}
}
答案 1 :(得分:1)
从文档中
可以在路径的尾部调用函数-函数的输入是路径表达式的输出
鉴于此语句,您可能希望上面提供的JSON示例可与$.store..price.max()
之类的表达式一起使用,但此表达式不起作用,而是引发错误:
聚集函数尝试使用空数组计算值
您可以在GitHub上的JsonPath issue中了解有关此内容的更多信息。
同时,这是一个有效的示例。
给出以下JSON:
{
"price": [
1.0,
2.0
]
}
JsonPath函数的工作方式如下:
$..price.min()
返回[1.0]
$..price.max()
返回[2.0]
$..price.sum()
返回[3.0]
以上内容已使用online evaluator进行了验证。