无法使用 jq 将 JSON 输出转换为 CSV 格式

blu*_*ndr 2 csv json flatten jq

我正在构建 AWS EBS 卷属性列表,以便可以使用 jq 将其作为 CSV 存储在变量中。我要将变量输出到电子表格中。

第一个命令给出了我正在使用 jq 查找的值:

aws ec2 describe-volumes | jq -r '.Volumes[] | .VolumeId, .AvailabilityZone, .Attachments[].InstanceId, .Attachments[].State, (.Tags // [] | from_entries.Name)'
Run Code Online (Sandbox Code Playgroud)

给出我想要的输出,如下所示:

MIAPRBcdm0002_test_instance
vol-0105a1678373ae440
us-east-1c
i-0403bef9c0f6062e6
attached
MIAPRBcdwb00000_app1_vpc
vol-0d6048ec6b2b6f1a4
us-east-1c
MIAPRBcdwb00001 /carbon
vol-0cfcc6e164d91f42f
us-east-1c
i-0403bef9c0f6062e6
attached
Run Code Online (Sandbox Code Playgroud)

但是,如果我将其转换为 CSV 格式以便可以将变量输出到电子表格,则该命令会崩溃并且不起作用:

aws ec2 describe-volumes | jq -r '.Volumes[] | .VolumeId, .AvailabilityZone, .Attachments[].InstanceId, .Attachments[].State, (.Tags // [] | from_entries.Name)| @csv'
jq: error (at <stdin>:4418): string ("vol-743d1234") cannot be csv-formatted, only array
Run Code Online (Sandbox Code Playgroud)

对于 EBS 卷,即使将 JSON 的顶层转换为 CSV 格式也会失败:

aws ec2 describe-volumes | jq -r '.Volumes[].VolumeId | @csv'
jq: error (at <stdin>:4418): string ("vol-743d1234") cannot be csv-formatted, only array
Run Code Online (Sandbox Code Playgroud)

这是我正在使用这些命令的AWS EBS Volumes JSON 文件(该文件已清除公司标识符,但是有效的 json)。

如何使用 jq 将此 json 转换为 CSV 格式?

Ini*_*ian 6

您只能应用于@csv数组内容,只需将过滤器括在 a 中,[..]如下所示

jq -r '[.Volumes[] | .VolumeId, .AvailabilityZone, .Attachments[].InstanceId, .Attachments[].State, (.Tags // [] | from_entries.Name)]|@csv'
Run Code Online (Sandbox Code Playgroud)

使用上面的内容可能仍然保留引号,因此join()在这里使用也是合适的

jq -r '[.Volumes[] | .VolumeId, .AvailabilityZone, .Attachments[].InstanceId, .Attachments[].State, (.Tags // [] | from_entries.Name)] | join(",")'
Run Code Online (Sandbox Code Playgroud)