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

如何用jq遍历JSON子元素并重复父级field1值输出指定格式?

当然可以用jq实现这个需求!

首先提个小细节:你给出的JSON里,child_field1和child_field2没有加双引号,这不符合JSON规范,jq会解析失败,所以先修正成有效的JSON格式:

{ 
  "field1":"foo", 
  "array":[ 
    {"child_field1":"c1_1", "child_field2":"c1_2"}, 
    {"child_field1":"c2_1", "child_field2":"c2_2"} 
  ]
}

接下来分两种场景给你对应的jq命令:

场景1:每个子元素结果单独一行输出

使用这条命令:

jq -r '.field1 as $parent | .array[] | [$parent, .child_field1, .child_field2] | join(",")' input.json

输出结果:

foo,c1_1,c1_2
foo,c2_1,c2_2

命令拆解:

  • -r:让jq输出原始字符串(不带引号),完全匹配你要的格式
  • .field1 as $parent:把父级的field1值存到变量$parent里,后续每个子元素都能直接复用这个值
  • .array[]:遍历array数组中的每一个子对象
  • [$parent, .child_field1, .child_field2]:把父级值和当前子元素的两个字段打包成一个临时数组
  • join(","):将临时数组的元素用逗号拼接成字符串

场景2:所有结果用空格分隔在同一行输出

如果想要得到foo,c1_1,c1_2 foo,c2_1,c2_2这样的单行结果,只需要把上面的结果再打包成数组,用空格连接即可:

jq -r '.field1 as $parent | [.array[] | [$parent, .child_field1, .child_field2] | join(",")] | join(" ")' input.json

输出结果:

foo,c1_1,c1_2 foo,c2_1,c2_2

这样就能完美实现你要的效果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:37:18