jq
Overview
jq is a lightweight command-line JSON processor. It slices, filters, maps, and transforms structured data the way sed/awk do for text lines.
Syntax
jq [options] <filter> [file...]
… | jq [options] <filter>Common Options
| Option | Description |
|---|---|
. |
Identity — pretty-print JSON |
-r |
Raw string output (no JSON quotes) |
-c |
Compact (one object per line) |
-s |
Slurp: read all inputs into one array |
-n |
Null input (build JSON from filter only) |
-e |
Exit non-zero if result is false/null |
--arg name value |
Bind a string variable for use as $name |
--argjson name json |
Bind a JSON-valued variable |
Key Use Cases
- Pretty-print API responses
- Extract fields for scripts
- Transform arrays of objects
- Build JSON from shell variables
- Validate presence of keys in CI
Examples with Explanations
Pretty-print stdin
curl -s https://api.github.com/repos/jqlang/jq | jq .Readable indentation for exploration.
Extract a field
jq -r .name package.json-r drops quotes so the value is shell-friendly.
Map a list of objects
jq -r '.items[] | [.id, .name] | @tsv' data.jsonTSV is easy to pipe into cut, sort, or spreadsheets.
Filter array elements
jq '.[] | select(.status=="active")' users.jsonselect keeps only matching objects.
Default / optional field
jq -r '.email // "missing"' user.json// provides a fallback when the path is null/false.
Build JSON from shell
jq -n --arg user "$USER" --arg host "$(hostname)" '{user:$user, host:$host, ts: now|todate}'Safe construction without hand-escaped quotes.
Count keys
jq 'keys | length' config.jsonQuick shape check on an object.
Understanding Output
jq prints the filter result as JSON by default. Use -r for bare strings. Errors go to stderr; exit status is non-zero on parse/filter failures (and with -e on false/null).
Notes & Pitfalls
- Always prefer
--arg/--argjsonover string-interpolating JSON by hand. - Filters are programs: learn
.,[],|,select,map,keys,has. - Package:
sudo apt install jqon Debian/Ubuntu.