I have ideal JSON:
{
"environments":[
{
"name":"test",
"release":"2.0"
},
{
"name":"prod",
"release":"1.0"
},
]
}
This file could be in any state:
- It can be empty file with just empty object { }
- It can have empty "environemnts" array
- It can have some entries in environment array but not the one we want to update
I need to update or create the "release" tag with given version under given environment.
I tried variations of:
(.environments[] | select(.name == "prod") | .release) = "3.0" // .environments += [{"name": "prod", "release": "3.0"}]
I also tried:
.environments
|= (map(.name) | index("prod")) as $ix
| if $ix
then .[$ix]["release"] = "2.0"
else . + [{name: "release", value: "2.0"}]
end
But it either fails on empty file. Or doesn’t create new entry.
I’m lost here.
2
Answers
You can add the new element everywhere and then delete the old prod release if it existed:
Tested on the following 4 files:
You could create an
INDEX
, then update the.prod
field. This way, it is either updated if it existed, or created if it didn’t. Afterwards, iterate over the items to restore the array. Using the?
operator when creating the stream takes care of the empty object case.This turns both
{}
and{"environments": []}
into:And updates the given sample (after removing the abundant comma) into:
Demo