应用过滤器后如何获取jq以打印有效的json

时间:2018-08-29 00:20:05

标签: json bash shell amazon-web-services jq

我正在研究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"
        }
    ]
}

任何帮助将不胜感激。

1 个答案:

答案 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"
  }
]