jq command on Linux (manipulates json files) [Basic Guide]

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”

Uirá Endy Ribeiro

Uirá Endy Ribeiro is a Software Developer and Cloud Computing Architect with a 23-year career. He has master's degrees in computer science and fifteen IT certifications and is the author of 11 books recognized in the IT world market. He is also Director at Universidade Salgado de Oliveira and Director of the Linux Professional Institute - LPI Director's Board.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Need help?