Cheatsheet: JQ

Find a jq filter, check its output, and try it with the same input in the playground.

Updated

How to use

Examples use jq 1.6+ core syntax.

Filters
Paste into the playground, or put inside single quotes after jq in your terminal. Filters do not include jq or CLI flags.
Terminal commands
Include jq and its flags. Quoting is for POSIX shells (sh, bash, zsh), not PowerShell or cmd.exe. If a command reads input.json, save its example input to that file first.
Example data
Expand Example for self-contained input and expected output. JSON output may be compacted; whitespace is not significant.
Streams vs. arrays
A stream is zero or more separate JSON values, not an array. Use [filter] or map(...) when you need one array.
Open playground

Start here

Run your first command, then try a filter with the same input.

Run jq in your terminal

printf '%s\n' '{"name":"Ada"}' | jq '.name'

Keep the entire input

.

Read fields

Navigate objects and arrays, or emit their contents as a stream.

Read a nested field

.address.city

Read a key containing punctuation

.address["postal-code"]

Get one array item

.skills[1]

Take a slice

.skills[0:2]

Emit each name

.people[] | .name

Filter records

Choose matching records and order the results.

Select matching records

.people[] | select(.age > 30)

Keep matches in an array

.people | map(select(.team == "platform"))

Sort records by a field

.people | sort_by(.age) | map(.name)

Find minimum and maximum records

.people | {youngest: min_by(.age).name, oldest: max_by(.age).name}

Reshape JSON

Construct objects, rename fields, and transform each array item.

Keep selected fields

{make, model}

Rename fields

{carMake: .make, carModel: .model}

Combine fields into a string

{car: "\(.make) \(.model)"}

Use a value as an object key

{(.make): .model}

Transform every array item

.people | map({name, ageYears: .age})

Edit JSON

Set, update, and remove fields while keeping the rest of an object.

Set or add a field

.active = true

Transform an existing field

.tags |= map(ascii_downcase)

Increment a counter

.count += 1

Delete unwanted fields

del(.debug, .temporary)

Arrays and collections

Count, group, combine, and deduplicate array values.

Count array items

.people | length

Group records by a field

.people | group_by(.team) | map({team: .[0].team, names: map(.name)})

Flatten nested arrays

flatten

Remove duplicate values

unique

Deduplicate records by a field

unique_by(.id)

Concatenate arrays

.left + .right

Objects and entries

Inspect keys and convert between objects and key/value entry arrays.

List object keys

keys

Transform object values

map_values({name, ageYears: .age})

Convert an object to entries

to_entries

Build an object from entries

from_entries

Rename all object keys

with_entries(.key |= ("env_" + .))

Strings and case

Concatenate, split, join, and change the case of text.

Concatenate strings

.first + " " + .last

Convert to uppercase

ascii_upcase

Convert to lowercase

ascii_downcase

Capitalize the first character

ascii_downcase | (.[0:1] | ascii_upcase) + .[1:]

Split a string into an array

split(",")

Join array items into a string

join(", ")

String matching

Find literal text, check patterns, and replace regex matches.

Check for a substring

contains("jq")

Check a prefix or suffix

{prefix: startswith("dev"), suffix: endswith(".json")}

Match a regular expression

test("^prod-"; "i")

Replace every matching substring

gsub("\\s+"; "-")

Math and totals

Calculate, round, and summarize numbers. jq 1.6 uses double-precision floating point, not exact decimal arithmetic.

Add, subtract, multiply, and divide

{sum: (.a + .b), difference: (.a - .b), product: (.a * .b), quotient: (.a / .b)}

Find a remainder (terminal only)

jq '.a % .b' input.json

Round down, up, or to nearest

{floor: floor, ceil: ceil, nearest: round}

Calculate a root and a power

{root: sqrt, square: pow(.; 2)}

Sum a numeric field

map(.amount) | add // 0

Calculate an average

if length == 0 then null else add / length end

Type and JSON conversion

Convert numbers and strings, or parse JSON embedded inside a string.

Convert a numeric string

tonumber

Convert a value to a string

tostring

Parse a JSON-encoded string

.payload | fromjson

Encode a value as JSON text

tojson

Output and shell flags

Run these complete commands in a POSIX shell, not in the filter editor. Save each shown input as input.json first unless the note says otherwise.

Print strings without JSON quotes

jq -r '.name' input.json

Print compact JSON

jq -c '.' input.json

Pass a string safely

jq --arg name 'Alice' '.name = $name' input.json

Pass a JSON value

jq --argjson cfg '{"env":"prod"}' '.config = $cfg' input.json

Merge a stream of JSON objects

jq -s 'reduce .[] as $item ({}; . * $item)' input.json

Create JSON without an input file

jq -n --arg name 'Ada' '{name: $name}'

Export records as CSV

jq -r '.people[] | [.name, .age] | @csv' input.json

Export records as TSV

jq -r '.people[] | [.name, .age] | @tsv' input.json

Check a condition in a shell script

jq -e '.ready == true' input.json

Missing values and logic

Handle absent data deliberately and encode small decisions in filters.

Supply a default value

.email // "unknown@example.com"

Access uncertain structures

.user?.profile?.email // "n/a"

Distinguish missing keys from null

has("email")

Default null without replacing false

if .enabled == null then true else .enabled end

Choose between two results

if .age >= 18 then "adult" else "minor" end

Choose among multiple results

if .score >= 90 then "excellent" elif .score >= 70 then "pass" else "retry" end

Variables, helpers, and reduce

Keep context with variables, compose jq functions, and fold collections into a result.

Keep parent context while iterating

.team as $team | .people[] | {name, team: $team}

Define a reusable helper

def isAdult: .age >= 18; {name, adult: isAdult}

Define a helper with a parameter

def with_prefix(prefix): prefix + ": " + .; .name | with_prefix("User")

Recursively merge objects

reduce .[] as $item ({}; . * $item)

Discover available helper functions

builtins | map(select(startswith("ascii_"))) | sort

FAQ