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:
$ sudo apt-get install jq
On Red Hat/CentOS/Fedora, the command to install jq is:
$ sudo yum 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
{
“first_name”: “Sarah”, “
surname”: “Silva”
}
{“
first-name”: “Ana”, “last 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 sort JSON items by a certain key, such as first-name:
$ cat nomes.json | jq -s -c 'sort_by (.first_name) |. [] '
{"first_name”: Ana”, "last name”:” Ferreira "}
{" first-name”: “Clara”, "last name”: Martins "}
{" first-name”: Emilio”, "last name”: “last name”: “Moura
"} {"first name”: “first name”:” Pereira "}
{" 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”
The sudo command on Linux executes a given command as if it were another user.…
The ss command on Linux is extremely useful for investigating sockets, providing various information about…
Free Linux command shows the amount of total memory in use and available, as well…
The shell has structures for testing conditions and executing certain program sequences several times (loop),…
The /etc/fstab file stores the configuration of which devices should be mounted and what is…
The Netcat Command in Linux or nc is a utility used to do “almost anything”…
This website uses cookies.