$_ CLI In Depth
Learning progress 0%
lesson performance tmux vim git

Processing JSON with jq

6 min read Module 18: Performance, Debugging & Power Tools Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:12

Filters take documents in and produce values out

jq reads JSON from standard input or from named files, and it prints the result of a filter, one value per line, as JSON. The simplest filter is the dot, which prints the whole document formatted. A key name after the dot selects a field, and brackets select array items. The filter .users[0].name reads the name of the first user in a document with a users array.

BASH1 lines
jq . data.json

The output is indented and colored on a terminal. The formatting is the first use of jq that many people find helpful, because a minified file becomes readable in one step.

Iterating and raw output

The brackets with nothing inside, as in .users[], iterate over every element. Each element is then passed on as a separate value, so the next part of the filter runs once per user. By default, strings are printed with their JSON quotes. The -r option prints raw strings, which is what you want when the output feeds another command.

BASH1 lines
jq -r ".users[].name" data.json

The -c option prints each value on one line in compact form, which is convenient for line-based tools such as sort and wc.

select and map

select keeps a value when its condition is true. The filter select(.active) keeps objects whose active field is true, and the pipe after it passes the kept objects on. map(f) applies a filter to each element of an array and returns a new array, which is a shorthand for an iteration wrapped in brackets. The two forms are common, and the choice is about readability.

BASH1 lines
jq -r ".users[] | select(.active) | .name" data.json

Read a filter from left to right. Each pipe gives the output of the left side to the right side as input. That is a different meaning of the pipe from the shell, but the reading habit is the same.

Arithmetic and aggregates

jq supports the four arithmetic operators, and it has built-in functions for arrays. add sums an array of numbers, and length counts its items. A filter that collects every age into an array with brackets, then adds them and divides by the length, computes an average. The result is a number, printed in full precision, so a rounded value needs a further step if you want fixed digits.

BASH1 lines
jq "[.users[].age] | add / length" data.json

The brackets build the array, the pipe passes it to add, and the division uses the result. The same pattern works for totals, counts of matching items, and maximums with max.

Exit status and errors

jq returns a non-zero status when the input is not valid JSON, and it prints a message that names the line and column. A filter that refers to a field that does not exist returns null rather than an error, which is worth knowing when a script expects a value. The -e option makes jq exit with status 1 when the last output is false or null, so a script can test a condition in a shell if statement.

Note

jq is installed on the lab machine, and its manual is online at the project site. The jq --help option lists the command-line flags, which is the quickest reference when you forget one.

Writing filters in files

A long filter belongs in a file. The -f option reads the filter from a file, which keeps the shell command short and makes the filter easy to test. Combining jq with the shell's own tools is the usual pattern: jq extracts and reshapes the data, and sort, uniq, and awk finish the job.

Building new objects

jq can build objects and arrays with the same syntax used for reading them. The filter {name: .name, age: .age} produces a new object with two fields, and the shorthand {name, age} does the same when the field names match. A filter that wraps the result in brackets returns an array, so a list of users can be reshaped into a list of short records in one step. This is the basis of most data cleanup with jq.

Keys and sorting

The keys function lists the field names of an object, and sort_by sorts an array by a value that the filter computes for each element. For example, sort_by(.age) orders users by age, and -r prints the sorted names one per line. Combining these with select gives a short report from a large file without writing a loop in the shell.

Handling missing and null values

Real data is often incomplete. A filter that reads a field from every user returns null for a user that lacks the field, and the null then goes into any calculation as a value of zero or as an error, depending on the operator. The alternative operator, written as // after an expression (as in .port // 80), returns a fallback when the value is missing, and select with a has check keeps only the objects that contain a field. Deciding which of these to use is part of writing a correct filter.

Working with text output

Once jq has produced the values you want, the raw option prints them as plain lines, and the usual text tools take over. Sort and uniq count repeated values, and cut or awk select columns from a table that jq printed with tabs. Keep the filter in one place and the text tools in a pipeline after it, so each stage is easy to test on its own.

Test every filter on a small sample first, with a file that has one object of each shape your data can take. A filter that works on the sample and fails on the real file usually misses a missing field or an empty array, and a three-object file exposes both cases in seconds. Keep the sample in the repository next to the filter, so the test can be rerun after every change.

jq also has a raw input option, -R, that reads each line of a file as a string, and a slurp option, -s, that reads the whole input into one array. Those two options turn a plain text log into structured data, which is a common first step before you apply a filter to a log file.

Terminal lab · 3 steps · real Linux in your browser

Query a JSON file with jq

Extract fields, filter objects, and compute a value from a JSON file.

01
Extract a field from each object
Create data.json with three users and then print the name of each user with -r, which removes the JSON quotes: ``bash cat > data.json <<'EOF' {"users":[{"name":"ada","age":36,"active":true},{"name":"linus","age":54,"active":false},{"name":"grace","age":85,"active":true}]} EOF jq -r '.users[].name' data.json > names.txt `` Open names.txt. It should list ada, linus, and grace on separate lines.
Show hint for step 1
.users[] iterates over the array. .name then reads one field from each object. Without -r the output keeps the quotes.
02
Filter objects with select
select keeps the values for which a condition is true. Keep only the active users and print their names: ``bash jq -r '.users[] | select(.active) | .name' data.json > active.txt `` Open active.txt. It should list ada and grace.
Show hint for step 2
The pipe inside the filter passes each user object to select. select(.active) keeps objects whose active field is true.
03
Compute an average with add and length
Collect every age into an array, add the numbers with add, and divide by length. Save the result: ``bash jq '[.users[].age] | add / length' data.json > average.txt `` Open average.txt. The value is 58.33 with more digits after the point.
Show hint for step 3
The brackets build an array of ages. add sums an array and length counts its items.
Check yourself Question 1 of 4
Concept Check Raw output flag recall

What does the -r option do in jq?

Recap & Key Takeaways

The dot filter formats a document, a field name selects a value, and brackets select array items or iterate over every element.
The -r option prints raw strings without JSON quotes, and -c prints compact one-line output for other tools.
select keeps values that match a condition, and map applies a filter to every array element.
add and length combine with brackets to compute totals and averages, and the result keeps full numeric precision.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue