Recently I came across a very nice tool to process JSON data from your terminal: jq.
jq is a nice tool to use in your command lines to filter and process JSON streams that you can link directly in your CLI pipes.
Installation
zsh> brew install jq # MacOS
zsh> jq --version
jq-1.6
Examples
jq can be used to prettify JSON inputs:
zsh> echo '{"fruits": ["apple", "peer", "banana"]}' | jq "."
{
"fruits": [
"apple",
"peer",
"banana"
]
}
It can also read directly from files:
zsh> cat >frenchmen.json<<EOF
heredoc> {"frenchmen": [{"name": "Napoleon"}, {"name": "Degaulle"}, {"name": "Exupery"}]}
heredoc> EOF
zsh> jq "." frenchmen.json
{
"frenchmen": [
{
"name": "Napoleon"
},
{
"name": "Degaulle"
},
{
"name": "Exupery"
}
]
}
You can access specific properties e.g. “name”:
zsh> jq '.frenchmen | .[].name' frenchmen.json
"Napoleon"
"Degaulle"
"Exupery"
You can slice through arrays:
zsh> echo '[1,2,3,4,5,6]' | jq ".[2:-1]"
[
3,
4,
5
]
You can also use functions:
zsh> echo '["blue", "white", "red"]' | jq '.[] | length'
4
5
3
zsh> echo '["blue", "white", "red"]' | jq '[.[] | length] | max'
5
zsh> echo '[1,2,3,4,5,6]' | jq '.[] | select(.%2==0)'
2
4
6
A more extensive list can be found in this article: https://www.baeldung.com/linux/jq-command-json