jq .[] 在更新键的值时从数组中删除对象

jq .[] removes objects from array when updating value for a key

我正在尝试更新基于 select 过滤器的键的值。该列表包含键名相同但值不同的字典。根据值,我过滤到 select 字典,然后更新其中的同级键。

值更新有效,但由于 .[],字典按预期移出列表,但如何将它们添加回列表。或者,我怎么能不使用 .[]?

输入列表:

[
    {
        "key1": "a",
        "key2": "b"
    },
    {
        "key1": "c",
        "key2": "d"
    },
    {
        "key1": "d",
        "key2": "e"
    }
]

命令我是运行: jq --arg temp "f" '.[] | select( .key1 == "c").key2 |= $temp' test.json

输出:

{
  "key1": "a",
  "key2": "b"
}
{
  "key1": "c",
  "key2": "f"
}
{
  "key1": "d",
  "key2": "e"
}

对象现在不在列表中。 预期输出:

[
    {
        "key1": "a",
        "key2": "b"
    },
    {
        "key1": "c",
        "key2": "f"
    },
    {
        "key1": "d",
        "key2": "e"
    }
]

我们如何将对象添加回列表,或就地添加。

使用map()保持原来的结构:

jq --arg temp  "f" 'map(select( .key1 == "c").key2 |= $temp)' test.json

Online demo

您也可以在更新分配的左侧使用另一对括号以保留上下文:

两种方法都有效:

jq --arg temp "f" '(.[] | select(.key1 == "c").key2) |= $temp' test.json

Demo

jq --arg temp "f" '(.[] | select(.key1 == "c")).key2 |= $temp' test.json

Demo