Blog Format and query JSON in the terminal with jq
Format and query JSON in the terminal with jq
TL;DR jq turns a wall of raw JSON into something readable and queryable. Pipe JSON into jq . to pretty-print, use .field to pick values, .[] to loop an array, and select() to filter. It is the fastest way to read and slice an API response in the terminal.
An API returns a compact blob of JSON and your terminal shows it as one unreadable line. jq fixes that, and does a lot more: it reads, filters, and reshapes JSON right in the pipe. A handful of patterns cover most of what you need.
Pretty-print anything
The simplest and most-used case: make JSON readable.
curl -s https://api.example.com/data | jq .
The . is the identity filter, it passes the data through, and jq indents and colourises it. That alone earns its place.
Pick a field
Drill into the structure with dot paths:
echo '{"user":{"name":"Ada"}}' | jq '.user.name' # "Ada"
Loop over an array
.[] iterates an array, so you can pull one field from every item:
curl -s https://api.example.com/users | jq '.[].email'
Filter with select
select() keeps only items that match a condition:
jq '.[] | select(.active == true)' # only active items
jq '.[] | select(.age > 30) | .name' # names of items over 30
Reshape the output
Build a smaller object from a bigger one:
jq '.[] | {name: .name, email: .email}'
Now you get just the fields you care about, in the shape you want.
Get raw strings, not quoted
By default jq quotes string output. -r gives you raw strings, handy for piping into other commands:
jq -r '.[].url' # one URL per line, no quotes
Why it beats opening a tool
The value of jq is staying in the pipe. Instead of copying a response into a formatter, or writing a throwaway script to pull one field, you slice the JSON right where it arrives. Learn pretty-print, field access, .[], and select(), and jq becomes the fastest way to read and question any JSON the terminal hands you.
FAQ
What is jq for?
It is a command-line tool for processing JSON. You pipe JSON into it and use a small query language to pretty-print, extract fields, filter, and transform the data, all without opening an editor or writing a script.
How do I pretty-print JSON with jq?
Pipe the JSON into jq with the identity filter: curl -s URL | jq . . That reformats a compact or messy response into indented, colourised JSON you can actually read.
Can jq filter arrays?
Yes. Use .[] to iterate an array and select() to keep only matching items, for example jq '.[] | select(.active == true)' to keep the active ones. You can combine filters to reshape the data as you go.