Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add element to json array using jq

Tags:

I'm adding strings to a JSON array using jq, and it works great, but I'd like to only add strings that do not already exist. I've experimented with unique, has, not, etc. I'm missing a piece or two to the puzzle.

Here's my starting json file, foo.json:

{
  "widgets": [
    {
      "name": "foo",
      "properties": [
        "baz"
      ]
    },
    {
      "name": "bar"
    }
  ]
}

Here's the jq command I've constructed that adds the string, even if it already exists:

$ cat foo.json | jq '.widgets[] | select(.name=="foo").properties |= .+ ["cat"]'

Here's the latest iteration of my attempt.

$ cat foo.json | jq '.widgets[] | select(.name=="foo").properties | has("cat") | not | .properties += ["cat"]'
jq: error: Cannot check whether array has a string key