1

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.

1 Answer 1

2

+ 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
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! I had a look through your link but wasn't sure if I could add in an array within the []. The post only spoke about a single value. Thanks a ton, worked like a charm!
Rather than updating the array to add to the array |= . + [...], just add to the array: += [...]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.