我有一个JSON文档,如下所示。请注意,这是真实JSON的简化示例,它包含在底部:
{
"some_array": [
{
"k1": "A",
"k2": "XXX"
},
{
"k1": "B",
"k2": "YYY"
}
]
}
我想更改k2
数组中所有some_array
个键的值,其中k1
键的值为“B”。
这可以使用jq吗?
作为参考,这是实际的JSON文档,它是用于postman / newman工具的环境变量文件。我正在尝试使用JQ进行此转换,因为该工具尚不支持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"
}
答案 0 :(得分:4)
以下是zayquan过滤器的一个稍微简单的版本:
.some_array |= map(if .k1=="B" then .k2="changed" else . end)
答案 1 :(得分:3)
这是另一种解决方案。
jq '(.some_array[] | select(.k1 == "B") | .k2) |= "new_value"'
输出
{
"some_array": [
{
"k1": "A",
"k2": "XXX"
},
{
"k1": "B",
"k2": "new_value"
}
]
}
答案 2 :(得分:2)
这是一个可行的解决方案:
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"
}
]
}