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

如何使用jq实现嵌套JSON文档的交集运算并处理结构差异报错

嵌套JSON对象交集的jq实现方案

核心实现代码

jq没有内置的深度交集方法,我们可以自定义递归函数实现,兼容对象、数组、基础值的嵌套场景,同时自带类型不一致的错误规避:

def deep_intersect($other):
  # 类型不匹配直接返回空,避免索引报错
  if type != $other.type then empty
  else
    type as $type
    | if $type == "object" then
        # 仅保留两个对象共有的键,对值递归计算交集
        reduce (keys_unsorted[] + ($other | keys_unsorted[]) | unique[]) as $k ({};
          ($other[$k] as $v2 | .[$k] = (.[$k] | deep_intersect($v2)))
        )
        # 过滤掉无有效值的空对象、空数组键
        | del(.[]. | select(. == {} or . == []))
      elif $type == "array" then
        # 按索引位置逐一计算交集,最后过滤空值
        [reduce range(0; (length | min($other.length))) as $i ([];
          . + [ (.[$i] | deep_intersect($other[$i])) ]
        ) | .[] | select(. != null and . != {} and . != [])]
      else
        # 基础类型完全相等才保留
        if . == $other then . else empty end
      end
  end;

# 适配输入为双元素JSON数组的场景(对应你的obj-list.txt结构)
.[0] as $obj1 | .[1] as $obj2 | $obj1 | deep_intersect($obj2)

执行命令为:
cat obj-list.txt | jq -f intersect.jq
或者直接把代码嵌在命令里执行:
cat obj-list.txt | jq 'def deep_intersect($other): if type != $other.type then empty else type as $type | if $type == "object" then reduce (keys_unsorted[] + ($other|keys_unsorted[])|unique[]) as $k ({}; ($other[$k] as $v2 | .[$k] = (.[$k] | deep_intersect($v2)))) | del(.[]. | select(. == {} or . == [])) elif $type == "array" then [reduce range(0;(length|min($other.length))) as $i ([]; . + [ (.[$i] | deep_intersect($other[$i])) ]) | .[] | select(. != null and . != {} and . != [])] else if . == $other then . else empty end end end; .[0] as $o1 | .[1] as $o2 | $o1 | deep_intersect($o2)'

错误校验说明

  • 代码内置类型前置校验逻辑,两个值类型不同时直接跳过该节点,不会抛出Cannot index number with string这类运行时报错
  • 如果需要明确标记结构不一致的字段,可把第一行的empty替换为{"error": "type_mismatch", "current_type": type, "target_type": $other.type},即可在结果中直接看到异常节点位置

适配调整说明

如果你的数组需要做无序交集(不按索引位置匹配,只要元素存在就算共有),可以把数组处理分支的代码替换为:

[ (. + $other) | unique[] | select(IN($other[])) ]

注意该方案仅适用于数组元素为基础类型的场景,复杂嵌套对象的无序匹配需要额外加判等逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:06:05