csvkit in2csv - 如何将单个 json 对象转换为两列 csv

csvkit in2csv - how to convert a single json object to two-column csv

正在寻找带有 csvkit 的单行文件。

来自普通 json 对象

{
  "whatever": 2342,
  "otherwise": 119,
  "and": 1,
  "so": 2,
  "on": 3
}

想要这个 csv

whatever,2342
otherwise,119
and,1
so,2
on,3

我基本上希望这个命令起作用,但它不起作用。

echo $the_json | in2csv -f json
> When converting a JSON document with a top-level dictionary element, a key must be specified.

似乎 csvkit 可以做一些事情,但我还没有找到合适的选项。

简答

变体 A:in2csv (csvkit) + csvtool

  • 将您的 json 括在方括号中
  • 使用 in2csv-I 选项来避免意外行为
  • 使用命令 transpose the two-row CSV, e.g. csvtool
echo "[$the_json]" | in2csv -I -f json | csvtool transpose -

变体 B:使用 jq 代替

这是一个仅使用 jq 的解决方案:(https://stedolan.github.io/jq/)

echo "$the_json" | jq -r 'to_entries[] | [.key, .value] | @csv'

取自How to map an object to arrays so it can be converted to csv?


长答案 (csvkit + csvtool)

输入

in2csv -f json 需要 个 JSON 个对象,因此您需要将单个对象 ({...}) 括在方括号 ( [{...}]).

在 POSIX 兼容的 shell 上,写入

echo "[$the_json]"

这将打印

[{
  "whatever": 2342,
  "otherwise": 119,
  "and": 1,
  "so": 2,
  "on": 3
}]

csvkit 命令

您可以将上述数据直接输入in2csv。但是,您可能 运行 遇到 csvkit 的“类型推断”(CSV 数据解释)功能的问题:

$ echo "[$the_json]" | in2csv -f json
whatever,otherwise,and,so,on
2342,119,True,2,3

1 变成了 True。有关详细信息,请参阅文档的 Tips and Troubleshooting 部分。建议使用 -I 选项关闭类型推断:

$ echo "[$the_json]" | in2csv -I -f json
whatever,otherwise,and,so,on
2342,119,1,2,3

现在结果符合预期

转置数据

不过,您需要 transpose the data. The csvkit docs say:

To transpose CSVs, consider csvtool.

csvtool 可在 github, opam, debian 和可能的其他分发渠道上使用。)

使用 csvkit + csvtool,您的最终命令如下所示:

echo "[$the_json]" | in2csv -I -f json | csvtool transpose -

连字符 (-) 表示从 stdin 中获取数据。这是结果:

whatever,2342
otherwise,119
and,1
so,2
on,3

就是这样。

我认为只有 csvtool 没有单行解决方案,您需要 in2csv。但是,您可以改用 jq,请参阅简短答案。

FTR,我使用的是 csvkit 版本 1.0.3

测试了第一个发布的答案有效!但这有点令人困惑,因为“[$the_json]”表示 json 的原始内容。所以命令的一个例子可能是这样的:

echo '[{"a":"b","c":"d"}]' | in2csv -I -f json | csvtool transpose -

如果您想用文件名代替,例如 myfile.json 可以使用 sed 命令添加括号并将其通过管道传输到 in2csv:

sed -e '1s/^/[/' -e 's/$/,/' -e '$s/,$/]/' myfile.json | in2csv -I -f json > myfile.csv

带有完整换位命令的示例:

sed -e '1s/^/[/' -e 's/$/,/' -e '$s/,$/]/' myfile.json | in2csv -I -f json | csvtool transpose - > myfile.csv

来源:How to add bracket at beginning and ending in text on UNIX