jq:如何替换数组中的元素或在不存在的情况下添加元素

时间:2019-10-04 15:56:51

标签: json jq upsert

给出以下json结构:

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

如果不存在jq元素以替换value元素的name: foo或将元素创建/添加到数组,该怎么做? >

1 个答案:

答案 0 :(得分:2)

这是行人解决方案的安全之处:

.elements 
|=  (map(.name) | index("foo")) as $ix
    | if $ix 
      then .[$ix]["value"] = "BAR" 
      else . + [{name: "foo", value: "BAR"}]
      end

您可能想抽象掉"foo""BAR"位:

upsert

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