About a month ago, I needed to parse JSON from in Bash scripts.
This was an interesting problem/challenge, enter ./jq.
jq is a sed like tool for JSON data, that can be used to parse JSON, from the command line, and from within Bash scripts.
jq is written in C, and is a single binary, that has zero runtime dependencies, meaning that you can simply download the binary and get parsing!
Some simple examples:
Lets say we have the following JSON payload:
sample.json:
[
{
"rank": 1,
"description": "Great Search Engine",
"url": "https://google.com"
},
{
"rank": 2,
"description": "Oldie but goodie",
"url": "https://www.yahoo.com"
}
]
If we wanted to print out the JSON payload in a colorized output, we could do:
cat sample.json | jq
The output would be:
Lets say we wanted just the URLs:
cat sample.json | jq .[].url
The output would be:
If we wanted just the first URL:
cat sample.json | jq .[0].url
This would ouput:
The URLs followed by the Ranks:
cat sample.json | jq '.[] | .url,.rank'
This would output:
Lets do something a little more complex, lets say we want to add 1 to every rank:
cat sample.json | jq '.[].rank +1'
This would output:
The above are just simple examples, jq is very powerful, and can do much more!
I recommend checking out the jq/ github page to get more information on this great tool.