给出以下json结构:
{
"elements": [
{
"name": "disregard",
"value": "me"
},
{
"name": "foo",
"value": "bar"
},
{
"name": "dont-edit",
"value": "me"
}
]
}
如果不存在jq
元素以替换value
元素的name: foo
或将元素创建/添加到数组,该怎么做? >
答案 0 :(得分:2)
这是行人解决方案的安全之处:
.elements
|= (map(.name) | index("foo")) as $ix
| if $ix
then .[$ix]["value"] = "BAR"
else . + [{name: "foo", value: "BAR"}]
end
您可能想抽象掉"foo"
和"BAR"
位:
# Input is assumed to be an array of {name:_, value:_} objects
def upsert($foo; $bar):
(map(.name) | index($foo)) as $ix
| if $ix then .[$ix]["value"] = $bar else . + [{name: $foo, value: $bar}] end;
用法:
.elements |= upsert("foo"; "BAR")