Search code examples
jsonjsonata

How to group the JSON object by a key using JSONata


I want to use JSONata to do the grouping of json objects in an array based on a key within the JSON object.

For example, I want to group the cars based on their names for the JSON example given below.

[
  {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
  },
   {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
  },
   {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
  }
]

Expected output

{
  "audi" : [
    {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
    },
    {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
    }
  ],
  "benz" : [
    {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
    }
   ]
}

Solution

  • $${car: [$.{"car": car, "color": color, "reg": reg}]}
    

    The documentation almost gives the solution:

    https://docs.jsonata.org/sorting-grouping

    To make sure that the values (even if there is only a single one) for each group is stored in an array, an explicit list construction with [...] is needed.