2

I have a json file which I am fetching from consul and the results are very simple:

[ { "name" : Jon", "class" : "senior" } ]

I want to update the array with below json:

{ "name" : santa", "class" : "christmas" }

and the output should be:

[ { "name" : Jon", "class" : "senior" }, { "name" : santa", "class" : "christmas" } ]

This looks very simple but I am unable to do it till now.

this is what I have been trying with jq:

JSON=[{ "name" : Jon", "class" : "senior" }]

echo $JSON | jq '.[] += { "new_key" : "new_value" }'

I followed some answers on stackoverflow but most of them are about adding a single element.

1
  • if you have input [ { "name": "Jon", "class": "senior" } ] { "name": "santa", "class": "christmas" } then filter input as $first | $first+[input] should work. jqplay.org/s/YsSEXxiWbQ Commented May 3, 2022 at 1:09

2 Answers 2

4

There are several issues with your script. Generally, this should work (but still needs improvement on certain levels):

JSON='[{"name": "Jon", "class": "senior"}]'
echo "$JSON" | jq '. += [{"new_key": "new_value"}]'
[
  {
    "name": "Jon",
    "class": "senior"
  },
  {
    "new_key": "new_value"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

2

This question is likely a duplicate of Add new element to existing JSON array with jq.

Anyway as a shortcut, here is how you do it without piping the source JSON array:

JSON='[{"name": "Jon", "class": "senior"}]'
jq --null-input --argjson  a "$JSON" '$a  + [{"name" : "santa", "class" : "christmas" }]'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.