I've a JSON:
[
{
"id": 3
},
{
"id": 1
},
{
"id": 2
}
]
I want to add additional key called order_id
to all objects in this json and set value as objects order in json (serial number). First object in json should have order_id
= 1, etc.... Amount of objects in json can be different, it's just example.
I expect this json: Expected result:
[
{
"id": 3,
"order_id": 1
},
{
"id": 1,
"order_id": 2
},
{
"id": 2,
"order_id": 3
}
]
You can use two stages of transformations such as
[ // replicate each objects' index within the array
//(they always start from 0 and increments by 1)
{
"operation": "shift",
"spec": {
"*": {
"*": "[#2].&", // replicate all existing attributes
"$": "[#2].order_id"
}
}
},
{ // increment each of those indexes by 1
"operation": "modify-overwrite-beta",
"spec": {
"*": {
"order_id": "=intSum(1,@(1,&))"
}
}
},
{ // sort by attributes' names
"operation": "sort"
}
]
the demo on the site http://jolt-demo.appspot.com/ is :