如何用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
相关产品推荐
相关产品推荐

