如何为jq数组中重复键值对的对应元素添加新键
为重复的JSON元素添加标记字段
给定如下JSON数组,其中包含多个带有foo:bar键值对的元素,要求保留所有元素,只为首次出现之后的foo:bar元素添加标记字段:
[ { "foo": "bar", "id": "baz" }, { "thud": "grunt", "id": "fum" }, { "foo": "bar", "id": "noot" }, { "zot": "toto", "id": "pluto" }, { "foo": "bar", "id": "toto" } ]
预期输出(标记字段内容可自定义,示例仅作说明):
[ { "foo": "bar", "id": "baz" }, { "thud": "grunt", "id": "fum" }, { "foo": "bar", "id": "noot", "desc": "duplicate found" }, { "zot": "toto", "id": "pluto" }, { "foo": "bar", "id": "toto", "desc": "duplicate found" } ]
解决方案:用jq实现
使用jq工具可以简洁完成这个需求,无需拆分合并JSON的复杂操作。执行以下命令(假设原始JSON保存在input.json文件中):
jq ' reduce .[] as $item ( {count: 0, result: []}; if $item.foo == "bar" then .count += 1 | if .count > 1 then .result += [$item + {"desc": "duplicate found"}] else .result += [$item] end else .result += [$item] end ) | .result ' input.json
命令说明
reduce遍历数组中的每个元素,同时维护两个状态:count(记录foo:bar元素的出现次数)和result(存储最终结果数组)- 当遇到
foo:bar的元素时,计数器加1;若计数器大于1,说明是重复项,为该元素添加desc字段后加入结果数组 - 非
foo:bar的元素直接加入结果数组 - 最后提取并输出结果数组
.result
如果需要自定义标记字段的内容(比如保留顺序编号),只需修改"desc"的值为"\(.count - 1)st duplicate found",即可匹配示例中的编号逻辑。
内容的提问来源于stack exchange,提问作者anantha
相关产品推荐
相关产品推荐

