I would like to use JSONata to reformat a JSON response into a different structure grouped by values in the object. I've searched StackOverflow but cannot see an example that matches my needs. I would like to turn this:
[
{
"group": "a",
"month": "01",
"value": "10"
},
{
"group": "a",
"month": "02",
"value": "20"
},
{
"group": "b",
"month": "01",
"value": "30"
},
{
"group": "b",
"month": "02",
"value": "40"
}
]
into this
{
"a": {
"01": "10",
"02": "20"
},
"b": {
"01": "30",
"02", "40"
}
}
The group values and months will change over time so it needs to be dynamic. Can anyone help?
Update: This is what I've tried so far which gets me close but not the exact structure I'm looking for:
${
$string(group): $.({
month: $.value
})
}
The result groups correctly but the months are in an array instead of an object:
{
"a": [
{
"01": "10"
},
{
"02": "20"
}
],
"b": [
{
"01": "30"
},
{
"02": "40"
}
]
}
How about:
${group: {month: value}}
This groups the initial array by the group
value. Then, the resulting array for each group is in turn grouped by month
.
Interestingly, JSONata understands that there is only one item per group now, and implicitly chooses the correct aggregation function, which simply returns the item.