【发布时间】:2021-02-16 14:26:01
【问题描述】:
我使用多个相同结构的 json 文件作为输入运行 jq,以输出单个 CSV 流,jq 脚本结尾如下:
| (map(keys) | add | unique) as $cols
| map(. as $row | $cols | map($row[.])) as $rows
| if (input_filename == "first-file.json" then $cols, $rows[] else $rows[] end
| @csv
第三行是为了避免为每个 JSON 文件重复 CSV 标头。这是一个丑陋的 hack,因为它对第一个输入文件名进行了硬编码。我想改用input_filenames[0],但没有这样的全局属性——还是我错过了它?还是有其他更简洁的方法来避免在输出 CSV 中重复标题行?
【问题讨论】:
-
你能分享几个这样的 JSON 文件的最小例子吗?
-
file1.json: [{"foo": 1, "bar": 2},{"foo": 3, "bar": 4}] file2.json: [{"foo" : 5, "bar": 6}] 调用为:jq -r -f script.jq file*.json