【问题标题】:dynamically changing values in multiple objects in json using jq使用jq动态更改json中多个对象的值
【发布时间】: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
      }
    }
  }
}

【问题讨论】:

  • 包装jqbash 代码并不真正相关。您能否专注于展示您期望modify_json 的结果是什么?
  • @chepner ,修改了问题部分的预期结果。

标签: json jq


【解决方案1】:

您可以(例如)简单地将以下内容添加到 jq 过滤器:

.anomalyDetection.loadingTimeThresholds.enabled = true |

【讨论】:

  • 好的,但是当把它作为变量时,它不会调用
  • 很抱歉,您的评论对我来说太模糊了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多