【问题标题】:Access to array of input filenames (or other way to output CSV header only once)访问输入文件名数组(或仅输出一次 CSV 标头的其他方式)
【发布时间】: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

标签: csv jq


【解决方案1】:

此回复仅解决发现以下问题:

仅输出一次 CSV 标头的方式

一种方法是使用input 处理第一个JSON 实体,然后使用inputs 处理其余部分,所有这些都使用jq 的-n 命令行选项。

input
| . as $in
| (map(keys_unsorted) | add | unique) as $cols
| $cols,
  (($in, inputs) | map(. as $row | $cols | map($row[.])))

还要注意这里使用keys_unsorted

【讨论】:

  • 谢谢,这很接近,但会产生: [ "bar", "foo" ] [ [ 2, 1 ], [ 4, 3 ] ] [ [ 6, 5 ] ] 和嵌套 borks @csv 错误“数组 ([2,1]) 在 csv 行中无效”所以还没有 quite :)
猜你喜欢
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
相关资源
最近更新 更多