【问题标题】:replace arguements in a json using jq使用 jq 替换 json 中的参数
【发布时间】:2020-11-18 03:01:46
【问题描述】:
{
"containers": [
          {
            "args": [
              "water",
              "fight",
              "--homein",
              "$(POD_NAMESPACE).svc.cluster.local",
              "--proxyLogLevel=warning",
              "--proxyComponentLogLevel=misc:error",
              "--log_output_level=default:info",
              "ms-madison",
              "--trust-domain=cluster.local"
            ]}]
}

我可以用一个丑陋的解决方案将 ms-madison 替换为 mr-harmison .containers[0].args[8] |= "mr-harmison"'

ms-madison 可以出现在任何位置。你能给我建议一个更好的方法来处理这个问题吗?

【问题讨论】:

    标签: json jq edit


    【解决方案1】:

    一个平淡但强大的解决方案:

    (.containers[0].args | index("ms-madison")) as $ix
    | if $ix then .containers[0].args[$ix] = "mr-harmison" else . end
    

    【讨论】:

      【解决方案2】:

      首先,这是一个完全不知道“ms-madison”出现在哪里的解决方案,但它会改变目标字符串的每次出现:

      walk(if . == "ms-madison" then "mr-harmison" else . end)
      

      其次,如果只想更改最多一次:

      . as $in
      | (first(paths | select(. as $p | $in | getpath($p) == "ms-madison")) // null) as $p
      | if $p then setpath($p; "mr-harmison") else . end
      

      限制对特定上下文的更改

      这是一个说明如何“走”.containers 以更改目标字符串的所有出现,这些目标字符串作为每个数组值“args”键的顶级元素出现:

      .containers |= walk( if type=="object"
                              and (.args|type)=="array"
                           then .args
                              |= map_values(
                                   if . == "ms-madison" 
                                   then "mr-harmison"
                                   else . end)
                           else . end)
      

      【讨论】:

      • 这个答案很有用。我无法对此投赞成票,因为它只允许我选择一个! @peak。
      猜你喜欢
      • 2017-03-14
      • 2018-08-17
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      相关资源
      最近更新 更多