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"
}

3 Answers 3

6

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

.some_array |= map(if .k1=="B" then .k2="changed" else . end)
Sign up to request clarification or add additional context in comments.

Comments

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"
    }
  ]
}

Comments

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"
    }
  ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.