parsing json in bash with pipe operators
Solution 1:
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.
Solution 2:
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};'