我需要获取亚马逊图像列表,并且需要显示的值之一是布尔值(真/假)。
例如,我可以毫无问题地从列表中提取图像ID:
cat oneimage.json | jq -r '.Images[] | [.ImageId] | @csv'
"ami-000bd263d51e443f2"
但是我需要添加到列表中的下一个值是一个true / false值,并且在下一个命令处出现jq扼流圈:
cat oneimage.json | jq -r '.Images[] | [.ImageId, ([.BlockDeviceMappings[].Ebs.DeleteOnTermination] | join(","))] | @csv'
jq: error (at <stdin>:89): string ("") and boolean (true) cannot be added
json包含卷列表。 “ DeleteOnTermination”值对于列表中的每个卷都是唯一的,并且必须以csv格式进入相同的“单元”。
目标是将csv输出到电子表格,并使所有DeleteOnTermination值在每个图像的单元格中的一行上用逗号分隔。
这是我用于此测试的json:
{
"Images": [{
"VirtualizationType": "hvm",
"Description": "AB-P-RIDD-TRAN05-12-13-2018",
"Hypervisor": "xen",
"ImageId": "ami-000bd263d51e443f2",
"State": "available",
"BlockDeviceMappings": [{
"DeviceName": "/dev/sda1",
"Ebs": {
"SnapshotId": "snap-0f1076dce3103833f",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 100,
"Encrypted": false
}
},
{
"DeviceName": "/dev/sdi",
"Ebs": {
"SnapshotId": "snap-0c7d71a9d3887a048",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 5,
"Encrypted": false
}
},
{
"DeviceName": "/dev/sdg",
"Ebs": {
"SnapshotId": "snap-00402196b9e023a72",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 10,
"Encrypted": false
}
},
{
"DeviceName": "/dev/sdk",
"Ebs": {
"SnapshotId": "snap-05f65a62735de2846",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 20,
"Encrypted": false
}
},
{
"DeviceName": "/dev/sdj",
"Ebs": {
"SnapshotId": "snap-0d350170b9d5c62bb",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 40,
"Encrypted": false
}
},
{
"DeviceName": "/dev/sdh",
"Ebs": {
"SnapshotId": "snap-04679d09d89609e79",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 30,
"Encrypted": false
}
},
{
"DeviceName": "/dev/sdf",
"Ebs": {
"SnapshotId": "snap-0b5f861fd93da6b20",
"DeleteOnTermination": true,
"VolumeType": "gp2",
"VolumeSize": 5,
"Encrypted": false
}
}
],
"Architecture": "x86_64",
"ImageLocation": "123456789191/AB-P-RIDD-TRAN05-12-13-2018",
"RootDeviceType": "ebs",
"OwnerId": "123456789191",
"RootDeviceName": "/dev/sda1",
"CreationDate": "2018-12-14T01:39:31.000Z",
"Public": false,
"ImageType": "machine",
"Name": "AB-P-RIDD-TRAN05-12-13-2018"
}]
}
如何使DeleteOnTermination值显示在一个csv单元格中,并用逗号分隔,每个卷中有一个DeleteOnTermination值?
答案 0 :(得分:2)
您需要使用tostring
。
.bool_value | tostring
您的情况下的用法:
jq -r '.Images[] | [.ImageId, ( [.BlockDeviceMappings[].Ebs.DeleteOnTermination | tostring] | join(",") )] | @csv' file
产量:
"ami-000bd263d51e443f2","true,true,true,true,true,true,true"
答案 1 :(得分:0)
这里是join
的定义,可以与jq的所有现有版本(即jq 1.3及更高版本)一起使用,并提供jq 1.6的灵活语义(即,仅要求所有数组中的项目为标量):
def join(c):
if length==0 then ""
else reduce .[1:][] as $x (.[0]|tostring; . + c + ($x|tostring))
end;
为便于参考:
tostring
在jq的所有现有版本中均可用;
jq 1.3没有join/1
(但确实有@csv
)。