【发布时间】:2021-06-27 18:06:22
【问题描述】:
以下文件取自Dynamically modify JSON file in bash script with jq - use heredocs or key assignments?
#!/usr/bin/env bash
function template {
cat<<EOF
{
"anomalyDetection": {
"loadingTimeThresholds": {
"enabled": false,
"thresholds": []
},
"outageHandling": {
"globalOutage": true,
"localOutage": true,
"localOutagePolicy": {
"affectedLocations": 1,
"consecutiveRuns": 2
}
}
}
}
EOF
}
function modify_json() {
template |
jq --argjson update_affectedLocations "${1:-1}" \
--argjson update_consecutiveRuns "${2:-2}" '
.anomalyDetection.outageHandling.localOutagePolicy
|= (.affectedLocations |= $update_affectedLocations
| .consecutiveRuns |= $update_consecutiveRuns )
'
}
updated_JSON=$(modify_json 42 666)
echo "$updated_JSON"
在此,除了.anomalyDetection.outageHandling.localOutagePolicy对象的上述变化外,如何在同一个modify_json函数中使用jq动态改变“.anomalyDetection.loadingTimeThresholds”对象中的.enabled.key。
上述脚本的实际输出如下
{
"anomalyDetection": {
"loadingTimeThresholds": {
"enabled": false,
"thresholds": []
},
"outageHandling": {
"globalOutage": true,
"localOutage": true,
"localOutagePolicy": {
"affectedLocations": 42,
"consecutiveRuns": 666
}
}
}
}
我期待这样的输出,现有值 anomalyDetection.loadingTimeThresholds.enabled 除了上述之外也将被替换为 true
{
"anomalyDetection": {
"loadingTimeThresholds": {
"enabled": true,
"thresholds": []
},
"outageHandling": {
"globalOutage": true,
"localOutage": true,
"localOutagePolicy": {
"affectedLocations": 42,
"consecutiveRuns": 666
}
}
}
}
【问题讨论】:
-
包装
jq的bash代码并不真正相关。您能否专注于展示您期望modify_json的结果是什么? -
@chepner ,修改了问题部分的预期结果。