JQ-通过通配符搜索深度替换子值并合并到原始JSON



我的问题类似于Unix jq解析通配符,但希望合并到原始JSON。

比如,输入JSON:

{
"a": {
"1": {
"c": "text1"
},
"999": {
"c": "text99"
}
}
}

我想操作内部的"c": "text1"并将其修改为"c": "newtext"。但是,还需要与原始JSON合并。IOW,它不是关于提取,而是关于操作。

预期输出:

{
"a": {
"1": {
"c": "newtext"
},
"999": {
"c": "text99"
}
}
}

我试过了:

.. | .c? |= (sub("^text1$";"newtext"))

但是,它抛出null (null) cannot be matched, as it is not a string

jqplay:https://jqplay.org/s/2nFAus6Umz

.c等于您想要的值时,只使用带有表达式的路径walk来选择对象类型

jq 'walk(if type == "object" and .c == "text1" then .c |= "newtext" else . end)'

jqplay演示

沿着你的尝试:

(.. | objects | select(has("c")) | .c) |= (sub("^text1$";"newtext"))

或者按照越来越简洁的顺序:

(.. | select(try has("c")) | .c) |= (sub("^text1$";"newtext"))
(.. | select(has("c")?) | .c) |= (sub("^text1$";"newtext"))

最新更新