6

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"
}
peak
  • 105,803
  • 17
  • 152
  • 177
zayquan
  • 7,544
  • 2
  • 30
  • 39

3 Answers3

6

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

.some_array |= map(if .k1=="B" then .k2="changed" else . end)
jq170727
  • 13,159
  • 3
  • 46
  • 56
4

Here's another solution.

jq '(.some_array[] | select(.k1 == "B") | .k2) |= "new_value"'

Output

{
  "some_array": [
    {
      "k1": "A",
      "k2": "XXX"
    },
    {
      "k1": "B",
      "k2": "new_value"
    }
  ]
}
user197693
  • 1,935
  • 10
  • 8
3

Here is a viable solution:

cat some.json | jq '.some_array = (.some_array | map(if .k1 == "B" then . + {"k2":"changed"} else . end))'

produces the output:

  "some_array": [
    {
      "k1": "A",
      "k2": "XXX"
    },
    {
      "k1": "B",
      "k2": "changed"
    }
  ]
}
zayquan
  • 7,544
  • 2
  • 30
  • 39