Izy- Izy- - 4 years ago 108
Bash Question

Adding a new array to already existing JSON file jq bash

Assume I have the following large json

{
"firsttag": {
"secondtag": [
{
"thirdtag": [
{
"someothertag": [
{
"sample":"else"
},
{
"targetBlank": true,
}
],
"interestingtag": [
{
"refId": "A",
"target": "abc",
},
{
"refId": "B",
"target": "bbb",
},
{
"refId": "C",
"target": "ccc",
}
],
},
},
"overwrite": true
}


My JSON might not be syntactically perfect but that's becuase I've edited out some stuff. Now what I want to do is, I want to add another input under
interestingtag
that's similar to the others. For example, I desire it like

"interestingtag": [
{
"refId": "A",
"target": "abc"
},
{
"refId": "B",
"target": "bbb"
},
{
"refId": "C",
"target": "ccc"
},
{
"refId": "D",
"target": "ddd"
}
],


But I'm not able to figure out how to do it. I can retrieve the right location using

jq '.firsttag.secondtag[0].thirdtag[0].interestingtag' myfile.json


But when I try the simple

jq '.firsttag.secondtag[0].thirdtag[0].interestingtag + {"refId": "D", "refID": "C"}' myfile.json


I get a

jq: error: array and object cannot be added


Any idea how I can do this? Or what I'm doing wrong?

Thanks for the help.

Answer Source

+ does not append elements to arrays. You want to merge arrays using |= .+ [...] as explained in this answer

jq '.firsttag.secondtag[0].thirdtag[0].interestingtag |= .+ [{"refId": "D", "refID": "C"}]' myfile.json
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download