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

Can't put JSON output into CSV format with jq

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

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

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

给出我想要的输出:

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

但是,如果我将其转换为 CSV 格式以便将变量输出到一个 spread sheet,该命令会崩溃并且不起作用:

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

即使将 JSON 的顶层转化为 EBS 卷的 CSV 格式也会失败:

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

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

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

您只能对数组内容应用 @csv,只需将您的过滤器包含在 [..] 中,如下所示

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

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

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

解决了另一个模糊的 jq 错误:

string ("xxx") cannot be csv-formatted, only array

在我的例子中,我不想要 jq 的 entire 输出,而是每个 Elastic Search document 我提供给 jq 作为 CSV 字符串打印在它自己的一行上。为了实现这一点,我只是 移动了括号以仅包含每行中要包含的项目 .

首先,通过将我的括号仅放在要包含在每行输出中的项目周围,我产生了:

jq -r '.hits.hits[]._source | [.syscheck.path, .syscheck.size_after]'
[
  "/etc/group-",
  "783"
]
[
  "/etc/gshadow-",
  "640"
]
[
  "/etc/group",
  "795"
]
[
  "/etc/gshadow",
  "652"
]
[
  "/etc/ssh/sshd_config",
  "3940"
]

将其通过管道传输到 | @csv 会在单独的一行上打印每个文档的 .syscheck.path 和 .syscheck.size_after 的值,用引号和逗号分隔:

$ jq -r '.hits.hits[]._source | [.syscheck.path, .syscheck.size_after] | @csv'
"/etc/group-","783"
"/etc/gshadow-","640"
"/etc/group","795"
"/etc/gshadow","652"
"/etc/ssh/sshd_config","3940"

或省略引号,遵循已接受答案中注明的模式:

$ jq -r '.hits.hits[]._source | [.syscheck.path, .syscheck.size_after] | join(",")'
/etc/group-,783
/etc/gshadow-,640
/etc/group,795
/etc/gshadow,652
/etc/ssh/sshd_config,3940