JQ - 深度 child 通过通配符搜索替换,但检查 parent 合并到原始 JSON 的存在
JQ - Deep child replace through wildcard search, but check parent presence with merge to the original JSON
这是对我之前问题的一种扩展
我想在替换 child 之前检查某些 parents 中是否存在特定键。 松散,翻译成CSS选择器,我想要像* > fixedKeyCheckPresence > * > fixedKeyCheckValue
这样的东西
输入:
{
"randomKey1": {
"randomKey2": [
{
"randomKeyUnderAnyLevel11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel23": {
"fixedKeyCheckValue": "Foo"
}
}
}
}
]
},
"randomKey11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel123": {
"fixedKeyCheckValue": "Foo"
}
}
}
}
预期输出:
{
"randomKey1": {
"randomKey2": [
{
"randomKeyUnderAnyLevel11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel23": {
"fixedKeyCheckValue": "Bar"
}
}
}
}
]
},
"randomKey11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel123": {
"fixedKeyCheckValue": "Bar"
}
}
}
}
尝试过: (.. | select(try has("fixedKeyCheckPresence")) | .fixedKeyCheckValue) |= (sub("^Foo$";"Bar"))
您可以将 walk
与 ..
结合使用:
jq 'walk(
(.fixedKeyCheckPresence? | .. |
select(has("fixedKeyCheckValue")?).fixedKeyCheckValue) |= sub("^Foo$";"Bar")
)' input.json
.fixedKeyCheckPresence?
负责查找对象键 fixedKeyCheckPresence
并保持其他一切不变。
然后在.fixedKeyCheckPresence
下,我们枚举所有sub-nodes和..
和select包含fixedKeyCheckValue
的对象。
这是对我之前问题的一种扩展
我想在替换 child 之前检查某些 parents 中是否存在特定键。 松散,翻译成CSS选择器,我想要像* > fixedKeyCheckPresence > * > fixedKeyCheckValue
输入:
{
"randomKey1": {
"randomKey2": [
{
"randomKeyUnderAnyLevel11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel23": {
"fixedKeyCheckValue": "Foo"
}
}
}
}
]
},
"randomKey11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel123": {
"fixedKeyCheckValue": "Foo"
}
}
}
}
预期输出:
{
"randomKey1": {
"randomKey2": [
{
"randomKeyUnderAnyLevel11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel23": {
"fixedKeyCheckValue": "Bar"
}
}
}
}
]
},
"randomKey11": {
"fixedKeyCheckPresence": {
"randomeKeyUnderAnyLevel123": {
"fixedKeyCheckValue": "Bar"
}
}
}
}
尝试过: (.. | select(try has("fixedKeyCheckPresence")) | .fixedKeyCheckValue) |= (sub("^Foo$";"Bar"))
您可以将 walk
与 ..
结合使用:
jq 'walk(
(.fixedKeyCheckPresence? | .. |
select(has("fixedKeyCheckValue")?).fixedKeyCheckValue) |= sub("^Foo$";"Bar")
)' input.json
.fixedKeyCheckPresence?
负责查找对象键 fixedKeyCheckPresence
并保持其他一切不变。
然后在.fixedKeyCheckPresence
下,我们枚举所有sub-nodes和..
和select包含fixedKeyCheckValue
的对象。