Terminal · intermediate
JSON on the command line with jq
jq parses JSON values and applies filters that select, construct, transform, or serialize structured results.
Why it matters
Format-aware JSON processing preserves types and nesting that text tools can accidentally corrupt when whitespace, escaping, or key order changes.
Mental model
How to reason about json on the command line with jq
A jq filter receives a stream of JSON values and produces zero or more JSON values; pipelines connect filters within jq's structured value model.
Analogy
It is a query engine working from a labeled tree, not a highlighter scanning how that tree happened to be printed as text.
Examples
See the boundary, not just the happy path
Worked example · Select active names
jq -r '.users[] | select(.active) | .name' response.json.users[] emits each array element, select keeps active objects, .name extracts the value, and -r writes strings without JSON quotes.
Worked example · Construct a smaller object
jq '{id: .request_id, count: (.items | length)}' response.jsonThe filter builds a new JSON object while retaining numeric type for count and safely handling printed formatting.
Avoid · Searching serialized JSON with grep
grep '"active": true' response.jsonEquivalent JSON can vary in whitespace, line breaks, key order, and escaping, so textual shape is not a stable query interface.
Common mistakes
Misconceptions to remove early
Using -r for non-string structure
Raw output mainly changes JSON strings; arrays and objects still serialize as JSON, so choose output format based on the downstream consumer.
Interpolating shell text into a jq program
Pass values with --arg or --argjson instead of building source code, which avoids quoting bugs and preserves intended types.
Quick check
Can you predict the result?
1. What does jq -r change when the output value is a JSON string?
- • It writes the string contents without JSON quotation and escaping syntax.
- • It recursively reads directories.
- • It rejects all non-string fields.
2. Why is jq safer than grep for selecting a JSON field?
Keep building