17

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?

1 Answer 1

26
$ 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, not extract it and add to it.

Or, if you want to hard-code the key in the jq expression put pass the value on the command line:

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

Or neater, using $ARGS.named:

jq --argjson new_key "$somevalue" '.array[] += $ARGS.named' <<<"$json"

Change --argjson to just --arg if the value you are adding is a string.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .