Json is widely used format these days. Parsing Json on bash command line is not straight forward. But fortunately there is a bash command line utility "jq" which make it very easy.

In this post, I will show you how to use Jq. Let us first install it.

On Centos, we can install it using following command.yum install jq

Let us start with some simple examples.

Bash parse json Using jq

echo '{"greetings": "hello world"}' | jq
"greetings": "hello world"

The above command is self explanatory. How about printing just the value of key.

echo '{"greetings": "hello world"}' | jq ".greetings"
"hello world"

."greetings" will extract the value as shown above.

We can print the keys with the following command.

echo '{"greetings": "hello world"}' | jq "keys"

Jq also works on Json arrays.

echo '[ {"no": 10}, {"no": 20} ]'
[ {"no": 10}, {"no": 20} ]

Let us get all the values from above JSON arary.

Here is how you can do that.

echo '[ {"no": 10}, {"no": 20} ]' | jq '.[].no'

We can also index the array and print a specific value. Let us say, we want to print the 2nd value in the array.

echo '[ {"no": 10}, {"no": 20} ]' | jq '.[1].no'

.[] will get all the items in the Json array. For each of those items, .[].no will extract and print the value.

Here is similar example but with nested content.

echo '[ {"no": 10}, {"no": 20}, {"nos":[20,30,40]} ]' | jq '.[2].nos'

We can also print the length of array using 'length' keyword.

echo '{"no1": 10, "no2": 20, "no3":[20,30,40]}' | jq 'length'

Bash parse Json from API using jq

Let us parse the stock options data from following yahoo API.

curl -s https://query2.finance.yahoo.com/v7/finance/options/amzn | jq 'keys'

Ok, so the main key in the above Json data is 'optionChain'

Ok, before we look further in to the data. We would store the above API data in Bash variable so that we have to read in data only once.

jsond=$(curl -s https://query2.finance.yahoo.com/v7/finance/options/amzn)

Ok now we have the json data in the bash variable. We can investigate it further using regular jq commands as shown below.

echo $jsond | jq '.optionChain.result' | jq '.[0]' | jq 'keys'
echo $jsond | jq '.optionChain.result' | jq '.[0].underlyingSymbol'

I hope by now you must have got an idea of what we can do with jq.

For completeness, let me mention another utility jo which is used to create json data on bash command line.

Create Json data on bash command line using jo

Install jo from https://github.com/jpmens/jo

Creating json is easy. Let us do a simple example.

jo greeting='Hello World'
{"greeting":"Hello World"}

We can do pretty print using -p flag.

jo greeting='Hello World' -p 
"greeting": "Hello World"

Another example

jo name=Alex job=layer -p 
"name": "Alex", 
"job": "layer"