jq:如何替换数组中的元素或在元素不存在时添加它

jq: How to replace element in an array or add it if it doesn't exist

给定以下 json 结构:

{
   "elements": [
      {
         "name": "disregard",
         "value": "me"
      },
      {
         "name": "foo",
         "value": "bar"
      },
      {
         "name": "dont-edit",
         "value": "me"
      }
   ]
}

什么是适当的 jq 查询来替换 name: foo 元素的 value 或 create/add 数组的元素,如果它还没有存在吗?

这是一个行人安全的解决方案:

.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")