jq is a small program that reads JSON, runs a filter you write against it, and prints the result. Instead of scrolling through a wall of API output or fighting grep on data that has no lines, you say what you want — a field, every element of an array, only the records that match a condition — and jq hands it back. The whole tool rests on one idea: a filter takes JSON in and produces JSON out, and you chain filters together with the pipe | exactly the way you chain commands in a shell. Once that clicks, everything from pulling one field to reshaping a whole document into a CSV is the same move repeated.
What you’ll accomplish
- Read a value out of a JSON document by field path and by array index.
- Iterate over arrays and objects, filter records with
select(), and reshape them withmap()and object construction. - Produce output your shell can use: raw strings with
-r, compact JSON with-c, and spreadsheet rows with@csv. - Pipe a live API response from
curlstraight into jq and extract exactly the fields you need. - Recognize the handful of errors every beginner hits and fix them.
Prerequisites
- jq installed. Check the version with
jq --version; you should see something likejq-1.7.1. Every distribution ships it (apt install jq,dnf install jq,brew install jq). - A shell (bash or zsh) and, ideally,
curlfor the live example. - A sample JSON file. This guide uses one small file called
servers.jsonthroughout so every command builds on the last. - Version note: jq 1.7 (2023) is the current line and what this guide targets. jq 1.6 is still common on older systems and behaves the same for everything here, with two caveats worth knowing: 1.7 added SQL-style and math functions and made a few edge cases stricter. If a filter works for you but fails for a colleague, compare
jq --versionfirst.
Create the sample file:
cat > servers.json <<'EOF'
{
"region": "ca-central-1",
"count": 3,
"servers": [
{ "name": "web-01", "cpu": 4, "gb": 8, "roles": ["web", "cache"], "active": true },
{ "name": "web-02", "cpu": 4, "gb": 8, "roles": ["web"], "active": true },
{ "name": "db-01", "cpu": 8, "gb": 32, "roles": ["db"], "active": false }
]
}
EOF
How it works
A jq program is a pipeline of filters. The JSON document enters on the left, flows through each filter in turn, and whatever the last filter emits is what jq prints. The pipe | between two filters means “take the output of the left filter and feed it, one value at a time, into the right filter” — the same contract as a shell pipe, except the things flowing through are JSON values, not lines of text.
That “one value at a time” part matters. Some filters emit a single value; others, like array iteration, emit a stream of several values, and every filter downstream runs once per value in the stream. This is why .servers[] | .name prints three names rather than an array: .servers[] produces three objects, and .name runs against each one.
Read the pipeline left to right and picture the data changing shape at each stage. That mental model is the whole tool.
Step-by-step
1. Start with the identity filter . — it returns its input unchanged. On its own it does nothing useful, but jq pretty-prints and colorizes the result, which makes . the fastest way to make a blob of JSON readable:
jq '.' servers.json
{
"region": "ca-central-1",
"count": 3,
"servers": [
{
"name": "web-01",
"cpu": 4,
"gb": 8,
"roles": [
"web",
"cache"
],
"active": true
},
{
"name": "web-02",
"cpu": 4,
"gb": 8,
"roles": [
"web"
],
"active": true
},
{
"name": "db-01",
"cpu": 8,
"gb": 32,
"roles": [
"db"
],
"active": false
}
]
}
2. Reach into a field with .field. Chain field names with dots to descend into nested objects, and use [n] to index into an array:
jq '.region' servers.json
"ca-central-1"
jq '.servers[0].name' servers.json
"web-01"
3. Iterate an array with .[]. Appending [] to an array explodes it into a stream of its elements. Combine it with a field access to pull that field from every element:
jq '.servers[].name' servers.json
"web-01"
"web-02"
"db-01"
The output is three separate JSON strings, not an array. To collect a stream back into an array, wrap the expression in brackets — see step 6.
4. Keep only what matches with select(). select(condition) passes its input through when the condition is true and drops it otherwise. Pipe the stream of servers into it to filter records:
jq '.servers[] | select(.active == true) | .name' servers.json
"web-01"
"web-02"
The db-01 record had "active": false, so select discarded it before .name ever ran.
5. Get shell-friendly output with -r. By default jq prints strings with their JSON quotes. The -r (raw) flag strips the quotes so the values drop straight into a shell variable or a loop. Notice this only affects strings — numbers print the same either way:
jq -r '.servers[] | select(.cpu > 4) | .name' servers.json
db-01
6. Reshape a list with map(). map(f) runs the filter f on every element of an array and collects the results into a new array. Unlike .[], it takes an array in and gives an array back:
jq '.servers | map(.name)' servers.json
[
"web-01",
"web-02",
"db-01"
]
You can compute with the collected values. Wrapping a stream in [ ] builds an array, and add sums a numeric array:
jq '[.servers[].cpu] | add' servers.json
16
7. Build a new object with {a: .x}. Object construction lets you rename and pick fields, dropping everything you did not ask for. Each key gets a filter that produces its value:
jq '.servers[] | {host: .name, cores: .cpu}' servers.json
{
"host": "web-01",
"cores": 4
}
{
"host": "web-02",
"cores": 4
}
{
"host": "db-01",
"cores": 8
}
8. Emit several values with a comma. A comma runs two or more filters against the same input and concatenates their outputs into one stream. It is the projection operator — handy for printing a couple of fields side by side:
jq -r '.servers[] | .name, .cpu' servers.json
web-01
4
web-02
4
db-01
8
9. Inspect structure with keys, length, and has. These built-ins answer “what is in here?” without you knowing the shape in advance. keys lists an object’s keys (sorted), length counts elements, and has("k") tests for a key:
jq 'keys' servers.json
[
"count",
"region",
"servers"
]
jq '.servers | length' servers.json
3
jq '.servers[0] | has("gb")' servers.json
true
10. Flatten to a table with @csv. Build an array of the fields you want, then pipe it into @csv (or @tsv), which formats one comma-separated line and quotes strings for you. @csv only works on arrays, and you almost always pair it with -r so the line is not itself wrapped in quotes:
jq -r '.servers[] | [.name, .cpu, .gb] | @csv' servers.json
"web-01",4,8
"web-02",4,8
"db-01",8,32
To add a header row, emit it with a comma before the data rows:
jq -r '["name","cpu","gb"], (.servers[] | [.name, .cpu, .gb]) | @csv' servers.json
"name","cpu","gb"
"web-01",4,8
"web-02",4,8
"db-01",8,32
11. Compact a stream with -c. For logs or for feeding another program, -c prints each JSON value on one line instead of pretty-printed:
jq -c '.servers[] | {host: .name, cores: .cpu}' servers.json
{"host":"web-01","cores":4}
{"host":"web-02","cores":4}
{"host":"db-01","cores":8}
Validate it works
The point of jq is turning live JSON into something usable, so drive it end to end against a real API. This asks the GitHub API for the jq project itself and pulls three fields into a small record:
curl -s https://api.github.com/repos/jqlang/jq | jq '{name, stars: .stargazers_count, lang: .language}'
{
"name": "jq",
"stars": 35198,
"lang": "C"
}
The star count will differ when you run it — that is live data. Two things to note in that filter: {name} is shorthand for {name: .name} (a bare key copies the same-named field), and everything after curl -s is one uninterrupted pipe from network to parsed record. Push it one step further and produce a CSV row directly, the shape you would append to a report:
curl -s https://api.github.com/repos/jqlang/jq | jq -r '[.full_name, .stargazers_count, .open_issues_count] | @csv'
"jqlang/jq",35198,152
That is the entire loop: fetch, filter, format, done — no temporary files, no intermediate script.
Troubleshooting
Cannot index array with string "name". You wrote.servers.namebutserversis an array, not an object. You have to iterate first:.servers[].name(or index one element,.servers[0].name). The mirror-image error,Cannot iterate over ..., means you put[]on something that is not an array.- The shell ate your quotes. Always wrap the jq program in single quotes:
jq '.servers[]'. With double quotes the shell tries to expand$,`, and!inside the program before jq ever sees it. When you need a shell value inside the filter, do not splice it with string juggling — pass it safely with--arg name valueand reference it as$name:jq --arg role web '.servers[] | select(.roles | index($role))' servers.json. - A missing field errors instead of yielding null. Accessing a key that does not exist gives
null, but iterating or indexing the wrong type raises an error and stops jq. Append?to swallow that error and keep going:.servers[]?or.maybe[]?. Pair it with the alternative operator//to supply a default:.nickname // "n/a". -rdid nothing to my numbers or objects.-ronly unwraps top-level strings. A number, boolean, or object prints identically with or without it. If you want a raw table, first reduce each row to strings or use@csv/@tsv, which handle the formatting.Cannot index string, or only the first object was processed. When an input is a stream of several JSON documents (one per line, as many APIs and log files emit), jq handles them one at a time by default. If your filter needs to see them together — to count them, or sum a field across all of them — read them into a single array with-s(slurp):jq -s 'map(.value) | add'. Without-s, a filter likeaddruns against each document separately and fails or gives a per-document answer.
When this is the wrong approach
jq is superb at extracting and reshaping JSON, and it stays readable up to a few piped stages. Past that it fights back. Multi-step logic with variables, branching, and lookups across documents is expressible in jq but painful to write and to read six months later — that is the moment to reach for Python (json module) or Node, where the same logic is ordinary code. jq also loads each document into memory; for genuinely huge or unbounded input, use its streaming parser (--stream) or a tool built for the volume rather than the default whole-document mode. And jq is a transformer, not a validator: to check a payload against a schema, use a JSON Schema validator instead. For a companion example of piping curl output into a diagnostic pipeline, see breaking down request latency with curl. The full filter reference lives in the jq manual, and you can experiment without installing anything at jqplay.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.