11

I'm using the AWS CLI client to get the status of a snapshot but the output is in JSON. eg.

{
    "DBClusterSnapshots": [
        {
            "AvailabilityZones": [
                "us-east-2a",
                "us-east-2b",
                "us-east-2c"
            ],
            "DBClusterSnapshotIdentifier": "...",
            "DBClusterIdentifier": "...",
            "SnapshotCreateTime": "2021-12-23T05:59:41.658000+00:00",
            "Engine": "aurora",
            "AllocatedStorage": 517,
            "Status": "copying",
            "Port": 0,
            "ClusterCreateTime": "2020-01-17T18:59:19.045000+00:00",
            "MasterUsername": "...",
            "EngineVersion": "5.6.mysql_aurora.1.22.1",
            "LicenseModel": "aurora",
            "SnapshotType": "manual",
            "PercentProgress": 0,
            "StorageEncrypted": true,
            "KmsKeyId": "...",
            "DBClusterSnapshotArn": "...",
            "SourceDBClusterSnapshotArn": "...",
            "IAMDatabaseAuthenticationEnabled": false,
            "TagList": []
        }
    ]
}

I can use a combination of grep and sed (| grep Status | sed 's/.*"Status": "//' | sed 's/",//') to isolate the status of "copying" BUT I was wondering if there was an easier way to parse the JSON in bash. eg. var['DBClusterSnapshots'][0]['Status']

neubert
  • 7,574
  • 39
  • 94
  • 156

2 Answers2

30

Yes, there are several different tools that have a full JSON parser and some form of query language (along the lines of XML having XPath).

  • jq -r .DBClusterSnapshots[0].Status

  • jshon -e DBClusterSnapshots -e 0 -e Status -u

But also nothing really stops you from writing a one-liner script in a language that does have a built-in JSON parser and outputs the wanted data:

  • python -c "import sys, json; data = json.load(sys.stdin); print(data['DBClusterSnapshots'][0]['Status'])"

  • perl -MJSON -E '$/=undef; $data=decode_json(<>); say $data->{DBClusterSnapshots}->[0]->{Status};'

grawity
  • 501,077
22

The AWS CLI tools have a built-in --query parameter that accepts a JMESPath expression to select a subset of the JSON output.

Your example would look something like this:

aws rds describe-db-cluster-snapshots --query "DBClusterSnapshots[0].Status"

The above command may produce quoted output like "copying" (with the quotes included), because the AWS CLI tools generate JSON literals by default.

If you want just the bare text copying (without quotes), add --output text to the above command line.

grnch
  • 335