7. JQ and the World of Structured Data
Query, filter, and reshape JSON from the command line
JSON has become the universal data format. APIs return it, config files use it,
logging systems emit it, and tools like Terraform and Kubernetes describe
infrastructure with it. But JSON is designed for machines — it's hard to read
on a terminal, and impossible to manipulate with traditional text tools like
grep and awk.
jq solves this. It's a command-line JSON processor with its own query
language — purpose-built for filtering, transforming, and reshaping JSON data.
If awk is the tool for columnar text, jq is the tool for structured data.
The Simplest Use: Pretty-Printing
curl -s https://api.example.com/status | jq .
The . filter means "the entire input." jq parses the JSON and prints it
with syntax highlighting and proper indentation. This alone makes it
indispensable.
Before and after
# Raw API response:
{"status":"ok","uptime":86400,"services":{"db":"healthy","cache":"healthy"}}
After jq .
{
"status": "ok",
"uptime": 86400,
"services": {
"db": "healthy",
"cache": "healthy"
}
}
Extracting Values
Object fields
Use .field to extract a value:
echo '{"name": "alice", "age": 30}' | jq '.name'
# "alice"
Chain fields with dots for nested objects:
echo '{"user": {"name": "alice", "address": {"city": "Portland"}}}' \
| jq '.user.address.city'
# "Portland"
Raw strings with -r
By default, jq outputs JSON — strings are quoted. Use -r for raw output:
echo '{"name": "alice"}' | jq -r '.name'
# alice (no quotes)
This is essential when piping jq output to other tools.
Array elements
echo '[10, 20, 30]' | jq '.[1]'
# 20
Negative indices count from the end:
echo '[10, 20, 30]' | jq '.[-1]'
# 30
Array slicing
echo '[0, 1, 2, 3, 4, 5]' | jq '.[2:5]'
# [2, 3, 4]
The Pipe Operator
Just like the Unix shell, jq uses | to chain filters. The output of
one filter becomes the input to the next:
echo '{"users": [{"name": "alice"}, {"name": "bob"}]}' \
| jq '.users | .[0] | .name'
# "alice"
This composability is what makes jq powerful. Simple filters combine into
complex queries.
Iterating Arrays: .[]
The .[] filter iterates over array elements (or object values), producing
each one as separate output:
echo '[1, 2, 3]' | jq '.[]'
# 1
# 2
# 3
This is the key to processing collections:
Extract all names from an array of objects
echo '[{"name":"alice"},{"name":"bob"},{"name":"carol"}]' \
| jq '.[].name'
# "alice"
# "bob"
# "carol"
Iterate over object keys and values
echo '{"a": 1, "b": 2, "c": 3}' | jq 'to_entries[] | "\(.key)=\(.value)"'
# "a=1"
# "b=2"
# "c=3"
Constructing New Objects and Arrays
Build a new object
echo '{"first": "Alice", "last": "Smith", "age": 30}' \
| jq '{ full_name: (.first + " " + .last), age }'
# { "full_name": "Alice Smith", "age": 30 }
When the key name matches the field name (like age above), jq uses the
shorthand { age } which means { "age": .age }.
Wrap results in an array with [ ]
echo '[{"name":"alice","score":85},{"name":"bob","score":92}]' \
| jq '[.[] | .name]'
# ["alice", "bob"]
The [...] around a filter collects all its outputs into a single array.
select — Filtering Elements
select(condition) keeps only elements where the condition is true:
Filter by a field value
echo '[{"name":"alice","role":"admin"},{"name":"bob","role":"user"},{"name":"carol","role":"admin"}]' \
| jq '.[] | select(.role == "admin") | .name'
# "alice"
# "carol"
Common conditions:
select(.age > 21)
select(.status == "active")
select(.name | startswith("a"))
select(.tags | contains(["urgent"]))
select(.value != null)
map — Transform Every Element
map(f) applies filter f to each element of an array and returns a new array:
echo '[1, 2, 3, 4, 5]' | jq 'map(. * 2)'
# [2, 4, 6, 8, 10]
echo '[{"name":"alice","score":85},{"name":"bob","score":92}]' \
| jq 'map({ name, grade: (if .score >= 90 then "A" else "B" end) })'
map(f) is equivalent to [.[] | f].
Sorting and Grouping
sort_by
echo '[{"name":"carol","age":25},{"name":"alice","age":30},{"name":"bob","age":22}]' \
| jq 'sort_by(.age)'
Reverse sort
jq 'sort_by(.score) | reverse'
group_by
echo '[{"dept":"eng","name":"alice"},{"dept":"sales","name":"bob"},{"dept":"eng","name":"carol"}]' \
| jq 'group_by(.dept) | map({ dept: .[0].dept, members: map(.name) })'
# [{"dept":"eng","members":["alice","carol"]},{"dept":"sales","members":["bob"]}]
unique_by
jq 'unique_by(.email)'
Arithmetic and String Operations
Math
echo '{"price": 42, "qty": 3}' | jq '.price * .qty'
# 126
String interpolation
echo '{"host":"db.local","port":5432}' | jq '"jdbc:postgresql://\(.host):\(.port)/mydb"'
# "jdbc:postgresql://db.local:5432/mydb"
\(expr) inside a string evaluates the expression and inserts the result.
String functions
| Function | Example |
|---|---|
length |
`"hello" |
split(sep) |
`"a,b,c" |
join(sep) |
`["a","b"] |
test(regex) |
`"hello" |
capture(regex) |
`"2026-04" |
ascii_downcase |
`"Hello" |
ltrimstr / rtrimstr |
`"hello.txt" |
Reducing and Aggregating
Built-in aggregators
echo '[10, 20, 30]' | jq 'add'
# 60
echo '[3, 1, 4, 1, 5]' | jq 'min, max, (add / length)'
# 1
# 5
# 2.8
reduce
For custom aggregation:
echo '[1, 2, 3, 4, 5]' | jq 'reduce .[] as $x (0; . + $x)'
# 15
The form is reduce EXPR as $var (INIT; UPDATE).
Conditionals
echo '{"status": 500}' | jq 'if .status >= 500 then "server error"
elif .status >= 400 then "client error"
else "ok" end'
# "server error"
Alternative operator: //
// provides a default when the left side is null or false:
echo '{"name": "alice"}' | jq '.nickname // .name'
# "alice"
Optional access: ?
The ? suffix suppresses errors for missing fields:
echo '[{"a":1},{"b":2}]' | jq '.[].a?'
# 1
Working with Multiple Files
jq can read from files directly:
jq '.users[] | .email' data.json
Slurp mode with -s
By default, jq processes each JSON value in its input independently.
-s (slurp) reads all inputs into a single array:
# Merge multiple JSON files
jq -s 'add' file1.json file2.json
Reading raw lines with -R
# Convert plain text lines to a JSON array
cat names.txt | jq -R . | jq -s .
Null input with -n
Generate JSON from scratch:
jq -n '{ timestamp: now | todate, version: "1.0" }'
Practical Recipes
Pretty-print an API response
curl -s https://api.github.com/repos/stedolan/jq | jq .
Extract specific fields from an API
curl -s https://api.github.com/repos/stedolan/jq \
| jq '{ name, stars: .stargazers_count, language }'
Process NDJSON (newline-delimited JSON) logs
# Each line is a separate JSON object
cat app.log | jq 'select(.level == "error") | { time: .timestamp, msg: .message }'
Convert JSON to CSV
echo '[{"name":"alice","age":30},{"name":"bob","age":25}]' \
| jq -r '.[] | [.name, .age] | @csv'
# "alice",30
# "bob",25
Flatten nested structure
echo '{"a":{"b":{"c":42}}}' | jq '[paths(scalars) as $p | { key: ($p | join(".")), value: getpath($p) }] | from_entries'
# {"a.b.c": 42}
Update a value in-place
jq '.version = "2.0"' package.json > tmp && mv tmp package.json
Or with sponge (from moreutils):
jq '.version = "2.0"' package.json | sponge package.json
Output Formats
| Flag | Format |
|---|---|
| (default) | Pretty-printed JSON |
-c |
Compact (one line per object) |
-r |
Raw string (no quotes) |
@csv |
CSV |
@tsv |
Tab-separated values |
@base64 |
Base64 encoding |
@html |
HTML-escaped |
@uri |
URI-encoded |
When to Use jq vs. Other Tools
| Task | Best tool |
|---|---|
| JSON querying and transformation | jq |
| YAML processing | yq |
| XML processing | xmlstarlet, xq |
| Columnar text | awk |
| Simple key extraction from flat JSON | grep + sed (in a pinch) |
| Complex data pipelines | Python |
jq excels when the data is JSON and the task is filtering, reshaping, or
aggregating. For anything beyond JSON, look for format-specific tools.
Summary
jq .pretty-prints JSON — the most basic and most common use.field,.[n], and.[]navigate objects, arrays, and iterate collections- Pipes (
|) chain filters, just like Unix shell pipes select()filters elements;map()transforms themsort_by,group_by, andunique_byorganize collections- String interpolation (
\()) and arithmetic work inside filters -routputs raw strings;-sslurps multiple inputs;-ccompacts output- For JSON on the command line,
jqis as essential asgrepis for text