Search code examples
jsonjsonata

JSONata - How to order by value of keys?


I have this JSON array of objects:

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).

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,


Solution

  • The first part of your expression, payload{name:$average(price)} produces an object, not an array, so there is nothing to order. Remember that in JSON, an object is an unordered set of name/value pairs. 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 }
    ]