The jq command is indispensable for manipulating data in JSON format, such as indenting, sorting, compressing, and displaying JSON keys.
It is not installed as standard on most distributions.
The jq package can be installed on Debian /Ubunto with the command:
$ <a data-id="1082" data-type="post" href="https://www.linuxcertification.academy/sudo-command-on-linux-privilege-scale-basic-guide/">sudo</a> <a data-id="1040" data-type="post" href="https://www.linuxcertification.academy/apt-get-and-apt-command-on-linux-install-packages-basic-guide/">apt-get</a> install jq
On Red Hat/CentOS/Fedora, the command to install jq is:
$ sudo <a data-id="998" data-type="post" href="https://www.linuxcertification.academy/yum-command-on-linux-installing-and-upgrading-packages-basic-guide/">yum</a> install jq
In the following examples, consider the following data in JSON format:
$ cat names.json {"first-name” ="Sarah”, "last name”: Silva "} {" first_name”: Ana”, "last name”: Ferreira "} {" first-name”: Emilio”, "last name”: “Moura"} {"first-name”: Clara”, "last name”: Martins "} {" first-name”: “José”, "last name”: Pereira "}
jq can be used to indent a JSON file to an elegant format. The “-C ” option colors the keys and items:
$ cat nomes.json | jq <br></br>{<br></br>“first_name”: “Sarah”, “<br></br>surname”: “Silva”<br></br>} <br></br>{“<br></br>first-name”: “Ana”, “last name”: <br></br>“Ana”, “last name”: <br></br><br></br><br></br>“Ferreira”} {“first-name”: “Emilio”, <br></br>“last name”: “Moura”<br></br>} <br></br>{<br></br>“first_name”: “Clara”,
“last name”: “Martins”
}
{
“first_name”: “José”,
“last name”: “Pereira”
}
jq can be used to sort JSON items by a certain key, such as first-name :
$ cat nomes.json | jq -s -c 'sort_by (.first_name) |. [] '<br></br>{"first_name”: Ana”, "last name”:” Ferreira "} <br></br>{" first-name”: “Clara”, "last name”: Martins "} <br></br>{" first-name”: Emilio”, "last name”: “last name”: “Moura<br></br>"} {"first name”: “first name”:” Pereira "} <br></br>{" first_name” ="Sarah “, "surname”: “Silva"}
The “-s ” option loads the values into an array, so that it is possible to apply a filter on them. The “-c ” option, on the other hand, compresses the result, instead of expanding it.
You can check the size of a particular item:
$ jq '.first_name |length' names.json 5 3 6 5 4
To show only the unique keys of a JSON:
$ jq -c 'keys' names.json | sort | uniq ["first_name”, "last name "]
Only one key can be filtered:
$ cat names.json | jq 'last name'
“Silva” “Ferreira” “Moura” “Martins” “Pereira”