I have this JSON data:
{
"success": true,
"module": {
"data": {
"item_i77f664a2": {
"id": "i77f664a2",
"tag": "item",
"fields": {
"cartItemId": 2012636322
},
"type": "biz"
}
}
}
}
And I want to add {"operation":"delete"}
right below cartItemId
and then save the JSON data to a file. The result that I want is like this:
{
"success": true,
"module": {
"data": {
"item_i77f664a2": {
"id": "i77f664a2",
"tag": "item",
"fields": {
"cartItemId": 2012636322,
"operation": "delete"
},
"type": "biz"
}
}
}
}
This is what I have tried:
jq '.module.data.item_i77f664a2.fields + {"operation":"delete"}' > data.json
But it doesn't save the JSON data with the output that I want like above. How do I fix it ?
This type of update is where the magic of +=
comes into play. With your input, the following invocation:
jq '.module.data.item_i77f664a2.fields += {"operation":"delete"}'
produces the output you indicate you want:
{
"success": true,
"module": {
"data": {
"item_i77f664a2": {
"id": "i77f664a2",
"tag": "item",
"fields": {
"cartItemId": 2012636322,
"operation": "delete"
},
"type": "biz"
}
}
}
}
However, I am not sure that this will produce what you want in similar circumstances, as you have referenced "item_i77f61ee2".
Thanks to @peak for his answer!
Just want to add,
Creating a blank json file:
echo "{}" > config.json
File Content:
{}
Then add properties to the file:
echo "$(jq '. += {"url": "https://url.com"}' config.json)" > config.json
File Content:
{
"url": "https://url.com"
}
One more property:
echo "$(jq '. += {"name": "a Name"}' config.json)" > config.json
File Content:
{
"url": "https://url.com",
"name": "a Name"
}
If you have variables set and want to use that value (ie. Azure Build Pipelines) you can pass in that value as an argument (urlarg
in this case):
URL="https://url.com"
echo "$(jq --arg urlarg "$URL" '. += {"url": $urlarg}' config.json)" > config.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With