Modifying array of key value in JSON jq Modifying array of key value in JSON jq shell shell

Modifying array of key value in JSON jq


It is enough to assign to the path, if you are using |=, e.g.

jq '  (.taskDefinition.containerDefinitions[0].environment[] |    select(.name=="DB_USERNAME") | .value) |= "new"' infile.json

Output:

{  "taskDefinition": {    "containerDefinitions": [      {        "name": "web",        "image": "my-image",        "environment": [          {            "name": "DB_HOST",            "value": "localhost"          },          {            "name": "DB_USERNAME",            "value": "new"          }        ]      }    ]  }}


Here is a select-free solution using |=:

.taskDefinition.containerDefinitions[0].environment |=  map(if .name=="DB_USERNAME" then .value = "new"      else . end)

Avoiding select within the expression on the LHS of |= makes the solution more robust w.r.t. the version of jq being used.


You might like to consider this alternative to using |=:

walk( if type=="object" and .name=="DB_USERNAME"       then .value="new" else . end)