jq Cheat Sheet

Core jq syntax, filters, selectors, arrays, objects, variables, sorting, grouping, formatting, and shell-friendly usage.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Getting Started

Basic invocation and output behavior.

Pretty-print JSON from stdin

Format JSON read from stdin with default pretty output.

bashANYjqpretty-printstdin
bash
echo '{"name":"alice","age":30}' | jq '.'
Notes

The identity filter `.` returns the input unchanged, but jq formats it nicely.

Read JSON file

Process a local JSON file.

bashANYjqfilepretty-print
bash
jq '.' data.json
Notes

Use jq directly on a file path instead of piping with `cat`.

Compact output

Emit compact JSON on one line per result.

bashANYjqcompactoutput
bash
jq -c '.' data.json
Notes

Useful for logs, NDJSON-like processing, or piping into other tools.

Raw string output

Print strings without JSON quotes.

bashANYjqraw-outputstrings
bash
echo '{"name":"alice"}' | jq -r '.name'
Notes

The `-r` flag is essential when you want shell-friendly plain text.

Run jq without input

Create JSON from scratch using null input mode.

bashANYjqnull-inputgenerate-json
bash
jq -n '{app: "cheatsheet", enabled: true}'
Notes

`-n` starts with no input document, which is ideal for generating JSON.

Disable color output

Print monochrome JSON for scripts or files.

bashANYjqcoloroutput
bash
jq -M '.' data.json
Notes

`-M` disables color even if your terminal supports it.

Sort object keys

Output JSON with keys in sorted order.

bashANYjqsort-keysformatting
bash
jq -S '.' data.json
Notes

Helpful for stable diffs and deterministic output.

Selectors and Paths

Pick values by key, path, and array index.

Get object property

Select a top-level property by key.

bashANYjqselectorsobject
bash
echo '{"name":"alice","age":30}' | jq '.name'
Notes

Returns the value of the `name` field.

Get nested property

Select a value from a nested path.

bashANYjqselectorsnested
bash
echo '{"user":{"profile":{"email":"a@example.com"}}}' | jq '.user.profile.email'
Notes

Dot chaining walks nested objects.

Optional selector

Avoid errors when a key may be missing.

bashANYjqoptionalselectors
bash
echo '{"user":{}}' | jq '.user.profile?.email'
Notes

The `?` suppresses errors for missing fields.

Get array element by index

Return an item from an array by position.

bashANYjqarraysindex
bash
echo '[10,20,30]' | jq '.[1]'
Notes

Array indexing is zero-based.

Slice an array

Return a subrange of elements.

bashANYjqarraysslice
bash
echo '[10,20,30,40,50]' | jq '.[1:4]'
Notes

This returns elements at indexes 1 through 3.

Iterate over array items

Emit each array element separately.

bashANYjqarraysiteration
bash
echo '["a","b","c"]' | jq '.[]'
Notes

`.[]` expands the array into multiple outputs.

Iterate object values

Emit each value in an object.

bashANYjqobjectsvalues
bash
echo '{"a":1,"b":2}' | jq '.[]'
Notes

On objects, `.[]` returns the values.

Check whether key exists

Return true if an object has a key.

bashANYjqhasobject
bash
echo '{"name":"alice"}' | jq 'has("name")'
Notes

Use `has()` for existence checks before dereferencing fields.

List object keys

Return the keys of an object as an array.

bashANYjqkeysobject
bash
echo '{"name":"alice","age":30}' | jq 'keys'
Notes

Useful for introspection and debugging unknown schemas.

List all JSON paths

Emit all existing paths inside a document.

bashANYjqpathsintrospection
bash
echo '{"user":{"name":"alice","roles":["admin"]}}' | jq 'paths'
Notes

`paths` helps inspect complex or unfamiliar nested JSON structures.

Arrays and Objects

Build, reshape, merge, and inspect collections.

Array length

Return the number of items in an array.

bashANYjqarrayslength
bash
echo '[1,2,3,4]' | jq 'length'
Notes

`length` works on arrays, strings, and objects.

Map each item to a property

Transform an array of objects into one field per item.

bashANYjqmaparrays
bash
echo '[{"name":"a"},{"name":"b"}]' | jq 'map(.name)'
Notes

`map()` applies a filter to each element and returns an array.

Sum array values

Add all numbers in an array.

bashANYjqaddarrays
bash
echo '[1,2,3,4]' | jq 'add'
Notes

`add` sums numeric arrays and can also merge arrays or strings depending on input.

Flatten nested arrays

Collapse one level or all levels of array nesting.

bashANYjqflattenarrays
bash
echo '[[1,2],[3,[4]]]' | jq 'flatten'
Notes

`flatten` recursively flattens nested arrays into one array.

Unique values

Remove duplicate items from an array.

bashANYjquniquearrays
bash
echo '[3,1,2,3,2]' | jq 'unique'
Notes

`unique` sorts and deduplicates.

Sort an array

Sort scalar array values.

bashANYjqsortarrays
bash
echo '[3,1,2]' | jq 'sort'
Notes

Use `sort_by()` for arrays of objects.

Sort array of objects by field

Order objects by a chosen property.

bashANYjqsort-byobjects
bash
echo '[{"name":"b","age":20},{"name":"a","age":30}]' | jq 'sort_by(.name)'
Notes

`sort_by(.field)` is common for reporting and reformatting API output.

Group array items by field

Group objects into buckets by a property.

bashANYjqgroup-byobjects
bash
echo '[{"team":"a","name":"x"},{"team":"a","name":"y"},{"team":"b","name":"z"}]' | jq 'group_by(.team)'
Notes

Input should already be sorted by the grouping field for predictable results.

Merge objects

Combine two objects with later keys overwriting earlier ones.

bashANYjqmergeobjects
bash
jq -n '{name:"alice",age:30} + {age:31,city:"SF"}'
Notes

The `+` operator merges objects shallowly.

Build new object

Construct an object from selected fields.

bashANYjqobjectsconstruct
bash
echo '{"id":1,"name":"alice","email":"a@example.com"}' | jq '{id, name}'
Notes

Object construction is central to jq transformations.

Filters and Conditions

Select, filter, update, and conditionally transform JSON.

Select objects matching condition

Filter array items based on a boolean expression.

bashANYjqselectfiltering
bash
echo '[{"name":"a","age":20},{"name":"b","age":35}]' | jq '.[] | select(.age >= 30)'
Notes

`select()` keeps only inputs that satisfy the condition.

Filter array and keep array output

Return matching elements as an array.

bashANYjqmapselectarrays
bash
echo '[{"name":"a","active":true},{"name":"b","active":false}]' | jq 'map(select(.active))'
Notes

Wrap `select()` with `map()` when you want an array back.

Fallback default value

Use a fallback when a value is null or missing.

bashANYjqdefaultnull
bash
echo '{"name":"alice"}' | jq '.email // "unknown@example.com"'
Notes

The `//` operator provides a default value.

Conditional expression

Branch based on input values.

bashANYjqifconditionals
bash
echo '{"score":85}' | jq 'if .score >= 80 then "pass" else "fail" end'
Notes

jq supports full conditional branching with `if ... then ... else ... end`.

Update field value

Set an object field to a new value.

bashANYjqupdateassignment
bash
echo '{"name":"alice","age":30}' | jq '.age = 31'
Notes

Assignment lets you modify existing JSON structures.

Increment numeric field

Increase a numeric value in place.

bashANYjqupdatemath
bash
echo '{"count":5}' | jq '.count += 1'
Notes

Arithmetic update operators work on matching scalar types.

Delete object key

Remove a field from an object.

bashANYjqdeleteobjects
bash
echo '{"name":"alice","password":"secret"}' | jq 'del(.password)'
Notes

`del()` is useful for sanitizing secrets or noisy fields.

Delete nested key

Remove a deeply nested field.

bashANYjqdeletenested
bash
echo '{"user":{"profile":{"ssn":"123","name":"alice"}}}' | jq 'del(.user.profile.ssn)'
Notes

You can target nested paths directly inside `del()`.

Drop null values from stream

Suppress null outputs entirely.

bashANYjqnullfiltering
bash
echo '[1,null,2,null]' | jq '.[] | select(. != null)'
Notes

Use `empty` or `select()` to suppress unwanted outputs.

Variables, Reduce, and Advanced Transformations

Use variables, accumulators, and custom reshaping patterns.

Capture value into variable

Store a subexpression and reuse it later.

bashANYjqvariablestransform
bash
echo '{"user":{"name":"alice"},"team":"eng"}' | jq '.user as $u | {name: $u.name, team: .team}'
Notes

The `as $var` syntax avoids repeating long paths.

Reduce array to sum

Aggregate values manually with `reduce`.

bashANYjqreduceaggregation
bash
echo '[1,2,3,4]' | jq 'reduce .[] as $n (0; . + $n)'
Notes

`reduce` is powerful for custom aggregations.

Reduce array into object map

Build an object keyed by a field.

bashANYjqreduceobjects
bash
echo '[{"id":1,"name":"a"},{"id":2,"name":"b"}]' | jq 'reduce .[] as $item ({}; .[$item.id|tostring] = $item.name)'
Notes

This pattern is common when converting lists into keyed lookup tables.

Transform object entries

Update every key-value pair in an object.

bashANYjqwith-entriesobjects
bash
echo '{"a":1,"b":2}' | jq 'with_entries(.key |= ascii_upcase)'
Notes

`with_entries()` is object-oriented `map()` over `to_entries` output.

Convert object to entries array

Represent an object as key-value entry objects.

bashANYjqentriesobjects
bash
echo '{"a":1,"b":2}' | jq 'to_entries'
Notes

Useful when you need to filter or sort by object keys or values.

Convert entries back to object

Turn key-value entry objects into a normal object.

bashANYjqentriesobjects
bash
echo '[{"key":"a","value":1},{"key":"b","value":2}]' | jq 'from_entries'
Notes

Often paired with `to_entries | map(...) | from_entries`.

Recursively transform all strings

Walk the document and mutate matching values.

bashANYjqwalkrecursive
bash
echo '{"name":"alice","nested":["dev","ops"]}' | jq 'walk(if type == "string" then ascii_upcase else . end)'
Notes

`walk()` is very useful for recursive normalization when available in your jq version.

Strings and Formatting

Join, split, encode, decode, and shape text output.

Join array into string

Join array items with a delimiter.

bashANYjqjoinstrings
bash
echo '["alice","bob","carol"]' | jq -r 'join(", ")'
Notes

Great for turning arrays into CSV-like text.

Split string into array

Break a string apart using a delimiter.

bashANYjqsplitstrings
bash
echo 'alice,bob,carol' | jq 'split(",")'
Notes

jq can move fluidly between strings and arrays.

String interpolation

Build human-readable text from JSON values.

bashANYjqstringsinterpolation
bash
echo '{"name":"alice","age":30}' | jq -r '"(.name) is (.age) years old"'
Notes

Interpolation is one of jq's most useful shell-reporting features.

Convert array to CSV row

Output a JSON array as CSV.

bashANYjqcsvformatting
bash
echo '["alice",30,"SF"]' | jq -r '@csv'
Notes

Use `@csv` for CSV-safe quoting and escaping.

Convert array to TSV row

Output a JSON array as tab-separated text.

bashANYjqtsvformatting
bash
echo '["alice",30,"SF"]' | jq -r '@tsv'
Notes

`@tsv` is useful for shell tables and spreadsheet imports.

URL-encode a string

Encode a string for use inside URLs or query parameters.

bashANYjquriencoding
bash
echo 'hello world@example.com' | jq -sRr @uri
Notes

`-sRr` slurps raw text and returns an encoded plain string.

Base64-encode string

Encode a string as base64.

bashANYjqbase64encoding
bash
echo 'hello world' | jq -sRr @base64
Notes

Useful for quick payload generation in scripts.

Base64-decode string

Decode a base64 string back to plain text.

bashANYjqbase64decoding
bash
echo '"aGVsbG8gd29ybGQ="' | jq -r '@base64d'
Notes

Input must be a JSON string containing base64 data.

Files, Slurp, and Streams

Read multiple inputs, raw lines, and streaming data.

Slurp inputs into one array

Read all JSON inputs and wrap them into an array.

bashANYjqslurpfiles
bash
jq -s '.' file1.json file2.json
Notes

`-s` slurps all input documents into one array before applying the filter.

Read raw lines as strings

Treat input as plain text lines instead of JSON.

bashANYjqraw-inputlines
bash
printf 'alpha
beta
' | jq -R '.'
Notes

`-R` makes jq treat each line as a raw string.

Read whole raw file as one string

Slurp plain text into one string value.

bashANYjqraw-inputslurp
bash
cat notes.txt | jq -Rs '.'
Notes

`-Rs` is useful when you need to embed or encode an entire file.

Convert JSON lines into array

Turn multiple JSON documents into a single array.

bashANYjqndjsonslurp
bash
printf '{"id":1}
{"id":2}
' | jq -s '.'
Notes

Great for NDJSON aggregation and batch transforms.

Use streaming parser

Process large JSON incrementally as path/value events.

bashANYjqstreamlarge-files
bash
jq --stream '.' large.json
Notes

Streaming mode is advanced but valuable for huge documents.

Include filename in results

Annotate output with the source file name.

bashANYjqfilesmetadata
bash
jq '{file: input_filename, value: .}' data.json
Notes

Useful when processing many input files together.

Recommended next

No recommendations yet.