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

如何用jq批量处理JSON文件列表并生成指定格式输出?

批量用jq处理JSON文件生成指定格式输出

问题背景

我有如下文件路径列表:

/path/to/dir1/f1.json
/path/to/dir2/f1.json
/path/to/dir1/f12.json
..

每个JSON文件内容格式为:

{"score": 0.98}

希望用jq批量处理这些文件,生成如下格式的输出:

/path/to/dir1/f1.json,0.76
/path/to/dir2/f1.json,0.89
/path/to/dir1/f12.json,0.98
..

已掌握单个文件的jq用法,需要实现批量处理并生成上述格式输出的管道命令及输出组装方法。


解决方案

场景1:从标准输入读取文件路径列表

如果你的文件路径来自其他命令输出(比如存放在file_list.txt里,或通过find生成),可以用xargs配合jq实现批量处理:

cat file_list.txt | xargs -I {} jq -r --arg path {} '$path + "," + (.score | tostring)' {}

解释:

  • --arg path {}:将当前处理的文件路径传入jq内部变量$path
  • $path + "," + (.score | tostring):直接组装成「路径,分数」的格式,tostring确保数值类型的score转为字符串,避免拼接异常

场景2:直接遍历指定模式的文件

如果要处理某个目录下(含子目录)的所有.json文件,可使用shell循环:

# 先开启bash的递归glob扩展(仅bash需要)
shopt -s globstar
for file in /path/to/**/*.json; do
  echo "$file,$(jq -r '.score' "$file")"
done

或者用find命令实现递归遍历:

find /path/to -name "*.json" -exec sh -c 'echo "$1,$(jq -r ".score" "$1")"' _ {} \;

容错处理(可选)

如果部分JSON文件可能缺失score字段或格式错误,可以添加默认值:

cat file_list.txt | xargs -I {} jq -r --arg path {} '$path + "," + (.score // "N/A" | tostring)' {}

这里// "N/A"表示当score不存在时,用N/A替代。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:02:18