[英]JSONata - How to order by value of keys?
I have this JSON array of objects:我有这个 JSON 对象数组:
payload:[
{name: "product1", price: 1.25},
{name: "product2", price: 1.35},
{name: "product1", price: 1.20},
{name: "product2", price: 1.30},
{name: "product3", price: 1.40}, etc
]
I'm trying to use JSONata to produce a new array with the average price for each product (grouped by product name) and ordered by the result of $average(price).我正在尝试使用 JSONata 生成一个新数组,其中包含每个产品的平均价格(按产品名称分组)并按 $average(price) 的结果排序。
payload{name:$average(price)}^(?) // what does ? need to be
I basically want to know how to reference the value of each key/value pair for sorting/order-by use.我基本上想知道如何引用每个键/值对的值以进行排序/按顺序使用。
Thanks,谢谢,
The first part of your expression, payload{name:$average(price)}
produces an object, not an array, so there is nothing to order.表达式的第一部分, payload{name:$average(price)}
产生一个 object,而不是一个数组,所以没有什么可订购的。 Remember that in JSON, an object is an unordered set of name/value pairs.请记住,在 JSON 中,object 是一组无序的名称/值对。 If you want to create an ordered array of objects, similar to your input data, but aggregated as you've done, then you can use the following:如果您想创建一个有序的对象数组,类似于您的输入数据,但您已经完成聚合,那么您可以使用以下内容:
payload{name:$average(price)} ~> $each(function($v, $n) {{
'name': $n,
'avg': $v
}}) ^(avg)
The last part of this orders the array by increasing average price.最后一部分通过增加平均价格对数组进行排序。 This produces the result:这会产生结果:
[
{ "name": "product1", "avg": 1.225 },
{ "name": "product2", "avg": 1.325 },
{ "name": "product3", "avg": 1.4 }
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.