简体   繁体   English

使用 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"
            ]}]
}

I am able to replace ms-madison with mr-harmison with an ugly solution .containers[0].args[8] |= "mr-harmison"'我可以用丑陋的解决方案 .containers[0].args[8] |= "mr-harmison"' 用 mr-harmison 替换 ms-madison

ms-madison can come at any position. ms-madison 可以出现在任何位置。 Can you suggest to me a better way to deal with this?你能给我建议一个更好的方法来处理这个问题吗?

A prosaic but robust solution:一个平凡但强大的解决方案:

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

First, here's a solution which is completely agnostic about where "ms-madison" appears but which will change every occurrence of the target string:首先,这是一个解决方案,它与“ms-madison”出现的位置完全无关,但会改变目标字符串的每次出现:

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

Second, if one only wanted to change at most one occurrence:其次,如果只想更改最多一次:

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

Restricting changes to a specific context限制对特定上下文的更改

Here's an illustration of how to "walk" .containers to change all occurrences of the target string that occur as top-level elements of every array-valued "args" keys:这是如何“走” .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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM