JQ - 通过通配符搜索替换深度子值并合并到原始值 JSON
JQ - Deep child value replace through wildcard search and merge to the original JSON
我的问题与类似,但想合并到原来的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
表达式为select对象类型的路径
jq 'walk(if type == "object" and .c == "text1" then .c |= "newtext" else . end)'
根据您的尝试:
(.. | objects | select(has("c")) | .c) |= (sub("^text1$";"newtext"))
或按简洁性递增的顺序排列:
(.. | select(try has("c")) | .c) |= (sub("^text1$";"newtext"))
(.. | select(has("c")?) | .c) |= (sub("^text1$";"newtext"))
我的问题与
说,输入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
表达式为select对象类型的路径
jq 'walk(if type == "object" and .c == "text1" then .c |= "newtext" else . end)'
根据您的尝试:
(.. | objects | select(has("c")) | .c) |= (sub("^text1$";"newtext"))
或按简洁性递增的顺序排列:
(.. | select(try has("c")) | .c) |= (sub("^text1$";"newtext"))
(.. | select(has("c")?) | .c) |= (sub("^text1$";"newtext"))