我正在研究jq过滤和结果输出,以输出到另一个接受JSON有效负载的程序中。考虑以下示例:
输入:
My-MBP:myorg myname$ aws ec2 describe-snapshots --owner-id 12345678 | jq '.Snapshots[] | select(.Description | contains("myorg-database-b"))'
结果:
{
"Description": "myorg-database-b redacted",
"Encrypted": false,
"VolumeId": "vol-1234",
"State": "completed",
"VolumeSize": 500,
"StartTime": "2018-08-28T17:52:14.000Z",
"Progress": "100%",
"OwnerId": "12345678",
"SnapshotId": "snap-2424"
}
{
"Description": "myorg-database-b redacted",
"Encrypted": false,
"VolumeId": "vol-23456",
"State": "completed",
"VolumeSize": 500,
"StartTime": "2018-08-28T19:01:18.000Z",
"Progress": "100%",
"OwnerId": "12345678",
"SnapshotId": "snap-5535"
}
无论我做什么,我都无法获得jq
来打印有效的JSON,因此无法将其通过管道传输到另一个程序中。
AWS最初的JSON是对象数组,为什么我不能找回有效的对象数组?我在这里做错什么了吗?
这是AWS有效负载通过管道插入jq
之前的样子:
{
"Snapshots": [
{
"Description": "myorg-database-b redacted",
"Encrypted": false,
"VolumeId": "vol-23456",
"State": "completed",
"VolumeSize": 500,
"StartTime": "2018-08-28T19:01:18.000Z",
"Progress": "100%",
"OwnerId": "12345678",
"SnapshotId": "snap-5535"
},
{
"Description": "myorg-database-b redacted",
"Encrypted": false,
"VolumeId": "vol-23456",
"State": "completed",
"VolumeSize": 500,
"StartTime": "2018-08-28T19:01:18.000Z",
"Progress": "100%",
"OwnerId": "12345678",
"SnapshotId": "snap-5535"
}
]
}
任何帮助将不胜感激。
答案 0 :(得分:2)
您可以将整个jq表达式包装在方括号中,以使其将过滤器输出收集到数组中(记录在Array construction section中):
'[ .Snapshots[] | select(.Description | contains("myorg-database-b")) ]'
导致:
[
{
"Description": "myorg-database-b redacted",
"Encrypted": false,
"VolumeId": "vol-23456",
"State": "completed",
"VolumeSize": 500,
"StartTime": "2018-08-28T19:01:18.000Z",
"Progress": "100%",
"OwnerId": "12345678",
"SnapshotId": "snap-5535"
},
{
"Description": "myorg-database-b redacted",
"Encrypted": false,
"VolumeId": "vol-23456",
"State": "completed",
"VolumeSize": 500,
"StartTime": "2018-08-28T19:01:18.000Z",
"Progress": "100%",
"OwnerId": "12345678",
"SnapshotId": "snap-5535"
}
]