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

如何使用jq对比JSON文件并提取匹配的ID项?

批量匹配JSON对象的解决方案

需求1:匹配_titles2.txt与titles.json的ID

思路

先从_titles2.txt中提取所有titleId组成数组,再遍历titles.json的嵌套结构,筛选出id与数组中值匹配的对象。

命令实现

方法1(无需临时文件,高效版)

jq --argjson ids "$(jq -r '.titleId' _titles2.txt | jq -nR '[inputs]')" '.. | objects | select(.id | IN($ids[]))' titles.json > matched_result1.json
  • jq -r '.titleId' _titles2.txt:提取_titles2.txt每行JSON的titleId并输出纯文本
  • jq -nR '[inputs]':将纯文本ID转为JSON数组
  • .. | objects:递归遍历titles.json的所有嵌套对象
  • select(.id | IN($ids[])):筛选出id存在于ID数组中的对象

方法2(分步生成临时文件)

如果需要保留ID数组文件,可分两步:

# 提取titleId并保存为JSON数组
jq -r '.titleId' _titles2.txt | jq -nR '[inputs]' > title_ids.json

# 筛选匹配项
jq --argfile ids title_ids.json '.. | objects | select(.id | IN($ids[]))' titles.json > matched_result1.json

需求2:匹配_titles2.txt与_titles3.txt的ID

思路

提取其中一个文件的ID集合,筛选另一个文件中ID匹配的对象;若需要同时输出两边的匹配项,可将其中一个文件转为ID映射后进行关联。

命令实现

场景1:仅输出_titles3.txt中匹配的项

jq --argjson ids "$(jq -r '.titleId' _titles2.txt | jq -nR '[inputs]')" 'select(.TITLEID | IN($ids[]))' _titles3.txt > matched_result2.txt
  • 逻辑同需求1,筛选_titles3.txt中TITLEID存在于_titles2.txt的titleId数组中的对象

场景2:同时输出两边匹配的对应项

jq -n '
  # 将_titles3的内容转为以TITLEID为键的映射表
  $titles3 | reduce inputs as $item ({}; .[$item.TITLEID] = $item)
  # 遍历_titles2的每一项,查找匹配的TITLEID项并组合输出
  | $titles2 | inputs as $item
  | if .[$item.titleId] then [$item, .[$item.titleId]] else empty end
' --argfile titles2 _titles2.txt --argfile titles3 _titles3.txt > matched_both.json
  • reduce inputs as $item ({}; .[$item.TITLEID] = $item):把_titles3.txt的每行JSON转为{TITLEID: 原对象}的结构,方便快速查找
  • 遍历_titles2.txt的项,若找到对应TITLEID的项,就将两边对象组合成数组输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:15:49