jq is to JSON what grep, sed and awk are to text: a small command-line program that filters, reshapes and summarises structured data, from a pretty-printed API response to a multi-gigabyte JSON log. If you work with REST APIs, cloud CLIs, CI pipelines, WP-CLI or structured logs, jq turns a wall of JSON into the three fields you actually need, in one line. This jq tutorial uses one small sample file throughout, so every command can be copied and checked. It covers paths, filters, aggregation, CSV export, updates, shell variables, exit codes for scripts, JSON Lines logs and live API calls. Every command was run with jq 1.7.1 and checked against jq 1.7 on Ubuntu 24.04, where sudo apt install jq installs it; on macOS use brew install jq.

From my own work: My most used jq command is not clever at all: piping a CLI or API response into jq -r with a path, to pull one ID or URL into a shell variable. Learning select, map and –arg covers almost everything else I need day to day; reduce and group_by come out for the occasional quick report.
The sample data
Save this as orders.json. It has a nested object, arrays inside arrays, a null value and a missing key, which are the cases that usually trip people up:
{
"store": "demo-shop",
"generated": "2026-11-29T08:00:00Z",
"orders": [
{"id": 1001, "customer": {"name": "Ana", "country": "BD"}, "status": "paid", "total": 59.90, "items": [{"sku": "KB-01", "qty": 1}, {"sku": "MS-07", "qty": 1}], "coupon": "WINTER10"},
{"id": 1002, "customer": {"name": "Ben", "country": "UK"}, "status": "refunded", "total": 19.99, "items": [{"sku": "MS-07", "qty": 1}]},
{"id": 1003, "customer": {"name": "Chen", "country": "BD"}, "status": "paid", "total": 120.00, "items": [{"sku": "MN-24", "qty": 1}, {"sku": "KB-01", "qty": 2}], "coupon": null},
{"id": 1004, "customer": {"name": "Dina", "country": "US"}, "status": "pending", "total": 35.50, "items": [{"sku": "CB-03", "qty": 5}]}
]
}
Basics: paths, arrays and raw output
A jq program is a filter. . is the whole input, .key walks into an object, [n] picks an array element, and | passes the output of one filter into the next:
jq '.store' orders.json # "demo-shop" (JSON string, with quotes)
jq -r '.store' orders.json # demo-shop (-r: raw output for shell use)
jq '.orders[0].customer.name' orders.json # "Ana"
jq '.orders | length' orders.json # 4
jq -c '.orders[-1] | {id, status}' orders.json # {"id":1004,"status":"pending"}
jq -c '.orders[1:3] | map(.id)' orders.json # [1002,1003]
jq -r '.orders[].customer.name' orders.json # .[] emits every element, one per line
# Ana
# Ben
# Chen
# Dina
-rprints strings without quotes. Use it whenever the output goes into a shell variable or another command.-cprints compact one-line JSON, handy for logs and line-based tools..[]is the iterator. It emits every element as a separate value, so the rest of the pipeline runs once per element.{id, status}is shorthand for{id: .id, status: .status}: build a new object from fields.
The official jq tutorial walks through the same ideas against a live API if you want a second set of examples.
Filtering with select()
select(condition) passes a value through when the condition is true and drops it otherwise. Combine it with the iterator to filter arrays:
# orders that are paid
jq -c '.orders[] | select(.status == "paid") | {id, total}' orders.json
# {"id":1001,"total":59.90}
# {"id":1003,"total":120.00}
# combine conditions with and / or; wrap in [ ] to get one array
jq -c '[.orders[] | select(.total > 30 and .customer.country == "BD") | .id]' orders.json
# [1001,1003]
# select(.coupon) keeps only truthy values: null and missing keys are dropped
jq -r '.orders[] | select(.coupon) | "(.id) used (.coupon)"' orders.json
# 1001 used WINTER10
# case-insensitive regex match
jq -c '.orders[] | select(.customer.name | test("^c"; "i")) | .id' orders.json
# 1003
Two jq rules explain most surprises here. Only false and null are falsy, so select(.coupon) drops both the explicit null and the missing key, while an empty string or 0 would pass. And a missing key is not an error: .coupon on order 1002 simply returns null.
Aggregating: add, reduce, group_by, sort_by
Wrap a stream in [ ] to collect it into an array, then summarise the array. This is where jq replaces a quick spreadsheet or a throwaway Python script:
# revenue from paid orders
jq '[.orders[] | select(.status == "paid") | .total] | add' orders.json
# 179.9
# units sold per SKU
jq -c 'reduce .orders[].items[] as $i ({}; .[$i.sku] += $i.qty)' orders.json
# {"KB-01":3,"MS-07":2,"MN-24":1,"CB-03":5}
# orders and revenue per country
jq -c '.orders | group_by(.customer.country)
| map({country: .[0].customer.country, orders: length, revenue: (map(.total) | add)})' orders.json
# [{"country":"BD","orders":2,"revenue":179.9},{"country":"UK","orders":1,"revenue":19.99},{"country":"US","orders":1,"revenue":35.50}]
jq -c '.orders | sort_by(-.total) | map(.id)' orders.json # [1003,1001,1004,1002]
jq '.orders | max_by(.total) | .id' orders.json # 1003
jq -c '[.orders[].items[].sku] | unique' orders.json # ["CB-03","KB-01","MN-24","MS-07"]
jq '.orders | map(.customer.name) | join(", ")' orders.json # "Ana, Ben, Chen, Dina"
addsums numbers, concatenates strings and arrays, and merges objects.reduce EXPR as $x (INIT; UPDATE)builds any accumulator;.[$i.sku] += $i.qtyworks even for the first occurrence because adding tonullreturns the number.group_by(f)sorts byfand returns an array of groups;.[0]of each group gives you the shared key.sort_by(-.total)sorts descending for numbers. For strings usesort_by(.name) | reverse.
Notice that jq printed 59.90 and 120.00 exactly as they were written. Since jq 1.7, number literals that pass through unchanged keep their original form; computed numbers such as the sum 179.9 are printed in shortest form. jq stores numbers as IEEE 754 doubles, which RFC 8259 names as the safe range for interoperability, so very large integer IDs can lose precision if you do arithmetic on them. Treat such IDs as strings.
Exporting CSV and TSV
Build an array per row and pipe it to @csv or @tsv. Always combine them with -r, otherwise each row is printed as a quoted JSON string:
jq -r '.orders[] | [.id, .customer.name, .status, .total] | @csv' orders.json
# 1001,"Ana","paid",59.90
# 1002,"Ben","refunded",19.99
# 1003,"Chen","paid",120.00
# 1004,"Dina","pending",35.50
# a header row plus tab-separated values, ready for column -t or a spreadsheet
jq -r '["id","customer","total"], (.orders[] | [.id, .customer.name, .total]) | @tsv' orders.json
# defaults with // for null or missing values
jq -r '.orders[] | "(.id)t(.coupon // "none")"' orders.json
# 1001 WINTER10
# 1002 none
# 1003 none
# 1004 none
@csv quotes strings and escapes embedded quotes; @tsv escapes tabs and newlines. The alternative operator // returns the right side when the left is null, false or produces nothing, which is the jq way to write a default value. Other formatters include @json, @html, @uri, @sh and @base64, all listed in the jq manual.
Updating, deleting and reshaping
Assignment returns the whole document with the change applied, so you can edit deep inside a file and keep everything else intact:
# set, update in place with |=, and delete keys
jq -c '.orders[0] | .status = "shipped" | .total |= . * 1.1 | del(.coupon) | {id, status, total}' orders.json
# {"id":1001,"status":"shipped","total":65.89}
# filter an array but keep the rest of the document
jq -c '.orders |= map(select(.status != "refunded")) | .orders | map(.id)' orders.json
# [1001,1003,1004]
# work with keys: to_entries, with_entries, from_entries
jq -c '.orders[0].customer | to_entries' orders.json
# [{"key":"name","value":"Ana"},{"key":"country","value":"BD"}]
jq -c '.orders[0].customer | with_entries(.key |= ascii_upcase)' orders.json
# {"NAME":"Ana","COUNTRY":"BD"}
echo '{"a": 1, "b": null, "c": 3}' | jq -c 'with_entries(select(.value != null))'
# {"a":1,"c":3}
# keep only some paths of a large document (jq 1.7+)
jq -c 'pick(.store, .orders[0].id)' orders.json
# {"store":"demo-shop","orders":[{"id":1001}]}
# "edit in place": jq has no -i flag, so write a temp file and rename it
jq '.orders[0].status = "shipped"' orders.json > orders.json.tmp && mv orders.json.tmp orders.json
= sets a value, |= updates a value using its current value, and arithmetic shortcuts such as += exist too. to_entries and with_entries turn an object into key and value pairs so you can rename, filter or transform keys. Because jq has no in-place flag, write to a temporary file and rename it; doing jq ... file > file truncates the file before jq reads it and leaves you with an empty file.
When you need to describe changes between two JSON documents rather than apply them, standard formats exist; see JSON Patch vs JSON Merge Patch.
Passing shell variables safely: –arg, –argjson, $ENV
Never paste shell variables into the jq program with string interpolation. A value with a quote breaks the program, and in scripts it is an injection risk. Pass values as jq variables instead:
# --arg passes a string, --argjson passes a JSON value (number, bool, object)
status=paid
jq -c --arg status "$status" '[.orders[] | select(.status == $status) | .id]' orders.json
# [1001,1003]
jq -c --argjson min 50 '[.orders[] | select(.total >= $min) | .id]' orders.json
# [1001,1003]
# environment variables through $ENV
MIN_TOTAL=100 jq -c '[.orders[] | select(.total >= ($ENV.MIN_TOTAL | tonumber)) | .id]' orders.json
# [1003]
# build JSON safely from shell values: quotes and special characters are escaped for you
jq -n -c --arg name "O'Brien "Ltd"" --arg email ana@example.com '{name: $name, email: $email, tags: ["new"]}'
# {"name":"O'Brien "Ltd"","email":"ana@example.com","tags":["new"]}
--arg always creates a string, so compare it with string fields or convert with tonumber. --argjson parses the value as JSON, so 50 is a number and true a boolean. Building request bodies with jq -n --arg is the most reliable way to produce valid JSON from a shell script: the quotes in O'Brien "Ltd" come out correctly escaped without any manual work. That is useful when signing and sending webhook payloads, as in webhook signature verification.
Exit codes and error handling for scripts
By default jq exits 0 whenever it can parse the input, even if your filter found nothing. In scripts, add -e so the exit status reflects the result:
# -e: exit status reflects the result (0 = truthy output, 1 = false/null, 4 = no output)
if jq -e '.orders[] | select(.id == 1001)' orders.json > /dev/null; then echo "order exists"; fi
# order exists
jq -e '.orders[] | select(.id == 9999)' orders.json; echo "exit: $?"
# exit: 4
# ? suppresses errors, try/catch handles them
jq -c '.orders[0].customer.address.city?' orders.json # null (missing keys are just null)
echo '["5", "x", "7"]' | jq -c '[.[] | tonumber?]' # [5,7]
echo '["5", "x", "7"]' | jq -c 'map(try tonumber catch null)' # [5,null,7]
| Situation | Exit status with -e |
|---|---|
Last output is anything other than false or null |
0 |
Last output is false or null |
1 |
| No output at all | 4 |
| Invalid JSON input, compile error or usage error | Non-zero, even without -e |
The postfix ? suppresses errors from a single expression, which is useful when some values have the wrong type, and try ... catch lets you substitute a value. Use them sparingly: hiding every error makes broken input look like empty input.
JSON Lines logs: one record per line
Structured logs are usually written as JSON Lines: one JSON object per line. jq reads a stream of JSON values naturally, so it runs the filter once per line without any special flags. Save these sample lines as app.log:
{"ts":"2026-11-29T08:00:01Z","level":"INFO","logger":"web","msg":"GET /","status":200,"ms":41,"request_id":"a1"}
{"ts":"2026-11-29T08:00:02Z","level":"ERROR","logger":"billing","msg":"gateway timeout","status":504,"ms":5003,"request_id":"b7"}
{"ts":"2026-11-29T08:00:02Z","level":"INFO","logger":"web","msg":"GET /pricing","status":200,"ms":88,"request_id":"c3"}
{"ts":"2026-11-29T08:00:03Z","level":"WARNING","logger":"web","msg":"slow query","status":200,"ms":1250,"request_id":"d9"}
{"ts":"2026-11-29T08:00:04Z","level":"ERROR","logger":"web","msg":"GET /checkout","status":500,"ms":17,"request_id":"e2"}
# one line per record: jq runs the filter on each line separately
jq -r 'select(.level == "ERROR") | "(.ts) (.logger) (.msg) [(.request_id)]"' app.log
# 2026-11-29T08:00:02Z billing gateway timeout [b7]
# 2026-11-29T08:00:04Z web GET /checkout [e2]
jq -c 'select(.ms > 1000) | {request_id, ms}' app.log
# {"request_id":"b7","ms":5003}
# {"request_id":"d9","ms":1250}
# -s (slurp) reads all lines into one array for counting and sorting
jq -s -c 'group_by(.level) | map({level: .[0].level, count: length})' app.log
# [{"level":"ERROR","count":2},{"level":"INFO","count":2},{"level":"WARNING","count":1}]
jq -s '[.[].ms] | add / length | floor' app.log # 1279 (average ms)
# for big files: -n with inputs reads records one at a time instead of slurping the whole file
jq -n '[inputs | select(.status >= 500)] | length' app.log # 2
# logs with some non-JSON lines: read raw lines and parse what parses
printf 'not jsonn{"level":"INFO"}n' | jq -R -c 'fromjson? | .level' # "INFO"
# turn an array into JSON Lines
jq -c '.orders[]' orders.json > orders.jsonl
- Without flags, every line is processed on its own, so filtering with
selectworks on files of any size with constant memory. -sslurps all lines into one array, which you need for counting, grouping and sorting across records. It loads the whole file into memory.-nwithinputsreads the records one at a time inside your program, a middle ground when you aggregate only part of a large file.-Rwithfromjson?reads raw lines and skips the ones that are not JSON, which happens when a library prints a plain-text warning into a JSON log.
To produce logs in this format from a Python service, with request IDs on every line, see Python logging best practices. For Lighthouse, WP-CLI and other tools that print JSON reports, the same patterns apply: wp plugin list --format=json | jq -r '.[] | select(.update == "available") | .name' lists plugins with updates, and Lighthouse CI JSON report analysis shows a larger report-processing example.
Working with API responses and curl
Pipe curl into jq to pull exactly what you need from an API. Use curl -fsS so HTTP errors fail the command instead of feeding an error page to jq:
# latest jq release and its Linux binary from the GitHub API
curl -s https://api.github.com/repos/jqlang/jq/releases/latest
| jq -r '.tag_name, (.assets[] | select(.name | test("linux-amd64$")) | .browser_download_url)'
# jq-1.8.2
# https://github.com/jqlang/jq/releases/download/jq-1.8.2/jq-linux-amd64
# fail a script when an API returns an error object instead of data
curl -fsS https://api.github.com/repos/jqlang/jq | jq -e '.stargazers_count > 0' > /dev/null && echo "API OK"
# API OK
The release version shown is from the day of testing; yours will be newer. With set -o pipefail in your script, a failing curl also fails the whole pipeline. For APIs that need authentication, read the token from an environment variable in the curl header and keep it out of your shell history and of the jq program itself.
jq cheat sheet
| Task | jq |
|---|---|
| Pretty-print | jq . file.json |
| One field as plain text | jq -r '.name' |
| Every element of an array | .items[] |
| Filter | .items[] | select(.price > 10) |
| Transform each element | map({id, name}) |
| Count | length or [...] | length |
| Sum | map(.total) | add |
| Group and count | group_by(.k) | map({k: .[0].k, n: length}) |
| Default for null | .x // "none" |
| Keys of an object | keys |
| Delete a field | del(.secret) |
| Sort keys in output | jq -S . |
| CSV row | [.a, .b] | @csv with -r |
| Shell value into jq | --arg name "$v" then $name |
| Fail when missing | jq -e '.field' |
Common jq mistakes
- Forgetting
-rand getting"value"with quotes in a shell variable. - Double quotes around the program. Use single quotes so the shell does not expand
$and backticks; pass shell values with--arg. - Expecting
.[]output to be an array. It is a stream of values. Wrap it in[ ]when you need an array. - Redirecting output to the input file, which empties it. Write to a temp file and
mv. - Using
-son huge files when a per-lineselectwould do. - Old jq versions. Functions such as
pick, added in jq 1.7, do not exist in jq 1.6, which is still the packaged version on Ubuntu 22.04. Check withjq --versionwhen a command from a newer guide fails. Release notes are on GitHub.
jq tutorial checklist
- Single-quoted programs;
-rfor text output,-cfor one-line JSON. .[]plusselect()for filtering,[ ]to collect results.map,group_by,reduceandaddfor reports.//for defaults;?andtryonly where bad input is expected.--argand--argjsonfor every shell value.-ein scripts so missing data fails the step.- JSON Lines processed per line;
-sonly when you need the whole set. curl -fsSin front of jq for API calls.
Want this done on your own server or site?
I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.
FAQ
What is jq used for?
jq is a command-line JSON processor. It is used to pretty-print JSON, extract fields from API responses and CLI output, filter and transform arrays, aggregate data into reports, convert JSON to CSV or TSV and query JSON Lines log files, usually as part of shell scripts and CI pipelines.
How do I get a value without quotes in jq?
Use the -r or –raw-output flag, for example jq -r .name file.json. Without it jq prints JSON, so strings include their double quotes. Use -r whenever the result goes into a shell variable or another command.
How do I filter an array in jq?
Iterate the array with .[] and keep matching elements with select, for example jq ‘.orders[] | select(.status == “paid”)’. Wrap the expression in square brackets, or use map(select(…)), if you want the result as a single array.
How do I pass a shell variable to jq?
Use –arg name “$value” for strings and –argjson name “$value” for numbers, booleans or JSON, then refer to $name in the program. Environment variables are also available as $ENV.NAME. Avoid building the jq program with shell string interpolation.
How do I convert JSON to CSV with jq?
Build an array for each row and pipe it to @csv with raw output, for example jq -r ‘.orders[] | [.id, .customer.name, .total] | @csv’ orders.json. Prepend a header array the same way, and use @tsv for tab-separated output.
Sources

Saizul Amin is a web developer, AI automation engineer and technical SEO consultant from Dhaka, Bangladesh (B.Sc. in CSE, BUBT). Since 2017 he has worked in digital marketing, WordPress, IT infrastructure and server administration, including the bilingual SHR Bangladesh website for DGHS, WordPress sites for UK and US clients, and the ShobFree tools platform. He runs this blog on his own Ubuntu VPS with nginx, Redis and CloudPanel, and tests the guides here on it. Portfolio: saizul.com

