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

jq替换JSON数组占位符时产生重复结果该如何解决

问题原因

原来的命令遍历input.json的每一个Id时,都会对全量的模板数组做替换,因此每个Id都会生成一个完整的数组,最终输出多组重复结果,不符合预期。

解决命令

针对你给出的两个等长数组的场景,直接按索引配对替换即可,命令如下:

jq -n --argjson inputs "$(<input.json)" --argjson tpl "$(<array.json)" '[$inputs, $tpl] | transpose | map(.[0].Id as $id | .[1] | .DataId = $id)'

命令逻辑说明

  • 通过--argjson把两个文件的内容直接作为参数传入jq,避免管道输入的遍历逻辑干扰
  • transpose会将两个等长数组按索引位置配对,形成[[input第1项, 模板第1项], [input第2项, 模板第2项]]的结构
  • 遍历每一组配对项,取出input项的Id赋值给对应模板项的DataId字段即可

通用扩展(可选)

如果模板中{{ID}}占位符可能出现在任意字段的任意位置,不是只替换整个DataId值,可以用字符串全局替换的写法适配更多场景:

jq -n --argjson inputs "$(<input.json)" --argjson tpl "$(<array.json)" '[$inputs, $tpl] | transpose | map(.[0].Id as $id | .[1] | walk(if type == "string" then gsub("\\{\\{ID\\}\\}"; $id) else . end))'

输出结果

最终生成的结构和array.json完全一致:

[
  {
    "DataId": "123456"
  },
  {
    "DataId": "7890123"
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:27:02