Here’s a fun tip for parsing json in bash using jq. This first example uses the jq library — you may need to install it for your flavor of linux.
#!/bin/bash
json='{"csp": "GCP",
"location":
{
"region": "us-east4",
"zone": "a"
},
"project": "project fun",
"services": ["GKE", "Cloud Run"]
}'
csp=$(echo $json | jq -r '.csp')
echo $csp
region=$(echo $json | jq -r '.location.region')
echo $region
zone=$(echo $json | jq -r '.location.zone')
echo $zone
project=$(echo $json | jq -r '.project')
echo $project
serviceA=$(echo $json | jq -r '.services[0]')
echo $serviceA
serviceB=$(echo $json | jq -r '.services[1]')
echo $serviceB
Here’s the output:
GCP
us-east4
a
project fun
GKE
Cloud Run
Here’s an example where we can use a jq docker container to accomplish the same task:
#!/bin/bash
json='{"csp": "GCP",
"location":
{
"region": "us-east4",
"zone": "a"
},
"project": "project fun",
"services": ["GKE", "Cloud Run"]
}'
# similar approach using docker
echo $json | docker run -i stedolan/jq '.csp'
echo $json | docker run -i stedolan/jq '.location.region'
echo $json | docker run -i stedolan/jq '.location.zone'
echo $json | docker run -i stedolan/jq '.project'
echo $json | docker run -i stedolan/jq '.services[0]'
echo $json | docker run -i stedolan/jq '.services[1]'
Here’s the output:
"GCP"
"us-east4"
"a"
"project fun"
"GKE"
"Cloud Run"