2

I have a json object stored in a shell variable json:

{
    "name": "foo",
    "array": [
        {
            "name": "bar",
            "thing": true
        },
        {
            "name": "baz",
            "thing": false
        }
    ]
}

I would like to add a new key (lets call it new_key) to both objects within array. I can do the following:

$ jq '.array[] + {"new_key": 0}' <<<"$json"
{
  "name": "bar",
  "thing": true,
  "new_key": 0
}
{
  "name": "baz",
  "thing": false,
  "new_key": 0
}

However that only returns the array array and not the entire object. How could I either modify the variable in place or return the entire object?

3
$ jq '.array[] += { "new_key": 0 }' <<<"$json"
{
  "name": "foo",
  "array": [
    {
      "name": "bar",
      "thing": true,
      "new_key": 0
    },
    {
      "name": "baz",
      "thing": false,
      "new_key": 0
    }
  ]
}

That is, use += in place of +. You want to modify the array array, not extract it and add to it.

If your data to add comes from shell variables that may need JSON encoding ($somevalue below), then you may use jo to produce the JSON fragment that you add:

jq --argjson newval "$( jo new_key="$somevalue" )" '.array[] += $newval' <<<"$json"

or, if you just want to pass the value and hard-code the key in the jq expression:

jq --arg newval "$somevalue" '.array[] += { new_key: $newval }' <<<"$json"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.