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:
Red Hat/AlmaLinux:
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:
Displays the entire data.json
file with syntax highlighting and indentation. The dot (.
) means everything
Extracting names:
.
- the entire JSON array[]
- iterate over its elements.name
- extract the value of thename
key from each object
Output:
Filtering by age:
select(...)
shows only elements that match the condition.age > 32
- checks the value of theage
field
Output:
Extracting all skills:
.skills[]
- flattens eachskills
array into individual elements
Output:
Unique list of skills:
[...]
- wraps everything back into a new arrayunique
- removes duplicates
Output:
Data Modification
Adding an active: true
field:
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:
Output:
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
wttr.in/Poznan?format=j1
- fetches weather data.current_condition[0].temp_C
- temperature in °C
Output:
Of course, depending on the current weather ;)
Validating JSON Format:
If the JSON is valid - there's no output. If it's invalid - you'll see a parse error
Used in Bash scripts:
Tools
- 🎮 Online playground: https://jqplay.org
- 🌦️ Weather API (no key): https://wttr.in/:help