Search code examples
jsoneditjqin-place

How do I update a single value in a nested array of objects in a json document using jq?


I have a JSON document that looks like the following. Note this is a simplified example of the real JSON, which is included at bottom of question:

{
  "some_array": [
    {
      "k1": "A",
      "k2": "XXX"
    },
    {
      "k1": "B",
      "k2": "YYY"
    }
  ]
}

I would like to change the value of all the k2 keys in the some_array array where the value of the k1 key is "B".

Is this possible using jq ?

For reference this is the actual JSON document, which is an environment variable file for use in postman / newman tool. I am attempting this conversion using JQ because the tool does not yet support command line overrides of specific environment variables

Actual JSON

{
  "name": "Local-Stack-Env-Config",
  "values": [
    {
      "enabled": true,
      "key": "KC_master_host",
      "type": "text",
      "value": "http://localhost:8087"
    },
    {
      "enabled": true,
      "key": "KC_user_guid",
      "type": "text",
      "value": "11111111-1111-1111-1111-11111111111"
    }
  ],
  "timestamp": 1502768145037,
  "_postman_variable_scope": "environment",
  "_postman_exported_at": "2017-08-15T03:36:41.474Z",
  "_postman_exported_using": "Postman/5.1.3"
}

Solution

  • Here is a slightly simpler version of zayquan's filter:

    .some_array |= map(if .k1=="B" then .k2="changed" else . end)