1

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.

  • if you have input `[ { "name": "Jon", "class": "senior" } ] { "name": "santa", "class": "christmas" }` then filter `input as $first | $first+[input]` should work. https://jqplay.org/s/YsSEXxiWbQ – Logan Lee May 03 '22 at 01:09

2 Answers2

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"
  }
]
pmf
  • 24,478
  • 2
  • 22
  • 31
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" }]'
Léa Gris
  • 17,497
  • 4
  • 32
  • 41