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

如何用jq为每行JSON对象添加[]包裹并生成合规JSON文件?

用jq处理多行JSON生成嵌套数组格式

问题场景

原始输入为每行一个独立JSON对象的文件:

{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}
{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}
{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}
{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}

需要生成每个JSON对象包裹在[]中,所有行整体再包裹在[]内的合规JSON格式:

[
  [{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}],
  [{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}],
  [{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}],
  [{"test":"index","test2":"fdsdfs","test3":"dfs0D0WOQAA3"}]
]

解决方案

使用以下jq命令即可实现:

jq -n '[inputs | [.]]' your-input-file.json

命令解释

  • -n:让jq不从标准输入读取初始值,而是通过inputs遍历所有输入行的JSON对象
  • inputs:逐个读取每行的独立JSON对象
  • [.]:将单个JSON对象包裹为单元素数组
  • 最外层的[]:将所有单元素数组收集到一个大数组中,形成最终的嵌套数组结构

如果需要紧凑输出(无换行缩进),可以添加-c参数:

jq -n -c '[inputs | [.]]' your-input-file.json

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:50:45