Skip to content

jq - JSON in the terminal

jq is a tool for working with JSON files. It allows filtering, extracting, modifying, and transforming data. Since it runs in the terminal, it's perfect for automation.

Installation

Usually available right after installing the system. If not:

Debian/Ubuntu:

apt install jq -y

Red Hat/AlmaLinux:

dnf install jq -y

Sample data.json file

We will use the following JSON content:

[
  {
    "name": "Ann",
    "age": 30,
    "skills": ["Python", "Bash"]
  },
  {
    "name": "John",
    "age": 35,
    "skills": ["Go", "Linux", "Docker"]
  }
]

Basics

Pretty-printing the JSON:

jq . data.json

Displays the entire data.json file with syntax highlighting and indentation. The dot (.) means everything


Extracting names:

jq '.[].name' data.json
  • . - the entire JSON array
  • [] - iterate over its elements
  • .name - extract the value of the name key from each object

Output:

"Ann"
"John"

Filtering by age:

jq '.[] | select(.age > 32)' data.json
  • select(...) shows only elements that match the condition
  • .age > 32 - checks the value of the age field

Output:

{
  "name": "John",
  "age": 35,
  "skills": ["Go", "Linux", "Docker"]
}

Extracting all skills:

jq '.[].skills[]' data.json
  • .skills[] - flattens each skills array into individual elements

Output:

"Python"
"Bash"
"Go"
"Linux"
"Docker"

Unique list of skills:

jq '[.[].skills[]] | unique' data.json
  • [...] - wraps everything back into a new array
  • unique - removes duplicates

Output:

["Bash", "Docker", "Go", "Linux", "Python"]

Data Modification

Adding an active: true field:

jq 'map(. + {active: true})' data.json

Adds a new active field to each object.

Output:

[
  {
    "name": "Ann",
    "age": 30,
    "skills": ["Python", "Bash"],
    "active": true
  },
  {
    "name": "John",
    "age": 35,
    "skills": ["Go", "Linux", "Docker"],
    "active": true
  }
]

Converting to CSV:

jq -r '.[] | [.name, .age] | @csv' data.json

Output:

"Ann",30
"John",35

jq + curl: Parsing API Data

The free weather API wttr.in allows fetching weather data in JSON format without an API key.

🔹 Example: weather in Poznan

curl -s 'https://wttr.in/Poznan?format=j1' | jq '.current_condition[0].temp_C'
  • wttr.in/Poznan?format=j1 - fetches weather data
  • .current_condition[0].temp_C - temperature in °C

Output:

"21"

Of course, depending on the current weather ;)


Validating JSON Format:

jq empty data.json

If the JSON is valid - there's no output. If it's invalid - you'll see a parse error

Used in Bash scripts:

if jq empty "$1" 2>/dev/null; then
  echo "JSON OK"
else
  echo "Invalid JSON"
fi

Tools