简体   繁体   中英

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"'

ms-madison can come at any position. 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:

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 |= walk( if type=="object"
                        and (.args|type)=="array"
                     then .args
                        |= map_values(
                             if . == "ms-madison" 
                             then "mr-harmison"
                             else . end)
                     else . end)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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