You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除JSON数组中的重复元素?

使用jq去除JSON对象中所有数组的重复元素

要给JSON对象里的每个数组去重,你可以用jq的map_values结合unique来实现,这是最简洁的方式:

jq 'map_values(unique)' input.json

为什么之前的方法没生效?

  • map是用来处理数组的,而你的数据是一个JSON对象,所以要用map_values来遍历对象的所有值(也就是各个数组)。
  • uniq需要数组先排序,而且它只去除连续的重复项,单独用它没法处理非连续的重复;而unique会自动去重并排序,刚好匹配你要的结果。

示例验证

输入JSON:

{
  "abc": [
    "five"
  ],
  "pqr": [
    "one",
    "one",
    "two",
    "two",
    "three",
    "three",
    "four",
    "four"
  ],
  "xyz": [
    "one",
    "one",
    "two",
    "two",
    "four"
  ]
}

执行命令后输出:

{
  "abc": [
    "five"
  ],
  "pqr": [
    "one",
    "two",
    "three",
    "four"
  ],
  "xyz": [
    "one",
    "two",
    "four"
  ]
}

保持原数组顺序的去重方法(可选)

如果你不想让数组排序,只想去除重复项并保留元素首次出现的顺序,可以用这个命令:

jq 'map_values([.[indexof($$)] // empty] as $seen | reduce .[] as $item ($seen; if index($item) then . else . + [$item] end))' input.json

内容的提问来源于stack exchange,提问作者Deepak Deore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:35:29