使用 jq 替换 json 中的参数

replace arguements in a json using jq

{
"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 可以出现在任何位置。你能给我建议一个更好的方法来处理这个问题吗?

首先,这里有一个解决方案,它完全不知道“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)

一个平淡无奇但稳健的解决方案:

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