如何使用 jq 更新 json 文档中嵌套对象数组中的单个值?

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

我有一个 JSON 文档,如下所示。请注意,这是真实 JSON 的简化示例,它包含在问题的底部:

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

我想更改 some_array 数组中所有 k2 键的值,其中 k1 键的值为 "B".

这可以使用 jq 吗?

作为参考,这是实际的 JSON 文件,它是用于 postman / newman tool. I am attempting this conversion using JQ because the tool does not yet support command line overrides of specific environment variables

的环境变量文件

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

这是一个可行的解决方案:

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

产生输出:

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

这是另一个解决方案。

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

输出

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

这里是 zayquan 过滤器的一个稍微简单的版本:

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