jq Cheat Sheet

The everyday jq set: selecting fields, filtering with select(), reshaping arrays and objects, strings, numbers, input modes, and output formats. Tested against jq 1.7.

Basics

jq . file.json                 # identity filter: pretty-print everything
jq -c . file.json              # compact output: one JSON object per line
jq -r .name file.json          # raw output: print strings without quotes
jq .name file.json             # shorthand: the filter is the program
echo '{"a":1}' | jq .          # read from stdin — jq loves pipes

Selecting fields

jq .name data.json              # object field
jq .meta.lang data.json         # nested field (dot chain)
jq '.["my key"]' data.json      # field with spaces or special chars
jq '.tags[0]' data.json         # first array element
jq '.tags[-1]' data.json        # last array element
jq '.tags[0:2]' data.json       # slice: elements 0 and 1 (end-exclusive)
jq -c '.tags[]' data.json       # iterate: one element per line
jq -c '.. | numbers' data.json  # recursive descent: every number anywhere
jq '.missing?' data.json        # optional: null instead of an error

Filters, pipes and commas

jq -c '.name, .stars' data.json      # comma: emit several results
jq '.tags | length' data.json        # pipe: feed left output into right
jq '.a | .b' data.json               # same as .a.b
jq '(.a + .b) * 2' data.json         # parentheses control grouping

Building JSON

jq -c '{n: .name, s: .stars}' data.json        # build an object from fields
jq -c '[.name, .meta.v]' data.json            # build an array
jq -r '"\(.name) has \(.stars) stars"' data.json   # string interpolation
jq -n '{today: "2026-10-15", n: (40+2)}'      # build from scratch (null input)
# note: {n: 40+2} is a syntax error — arithmetic in {} needs parentheses

Filtering with select()

jq -c '.[] | select(.in_stock)' items.json                 # keep matching elements
jq -c '[.[] | select(.price > 5 and .id != 2)]' items.json  # comparisons: == != > >= < <=
jq -c '[.[] | select(.in_stock | not)] | length' items.json # not: invert the test
# and / or / not combine tests; select() drops elements that fail

Arrays: reshape

jq -c 'map(.price)' items.json          # transform every element
jq -c 'map_values(.+1)' obj.json        # transform every object value
jq -c flatten nested.json               # flatten nested arrays, any depth
jq -c unique tags.json                  # sort + deduplicate
jq -c 'sort_by(.price) | map(.id)' items.json  # sort objects by a field
jq -c reverse arr.json                  # reverse order
jq -r 'join(", ")' arr.json             # join strings with a separator
jq add nums.json                        # sum numbers (also merges objects)

Arrays: inspect

jq '.tags | length' data.json           # number of elements
jq -c keys data.json                    # sorted key names of an object
jq 'has("stars")' data.json             # true if the key exists
jq '.tags | contains(["tools"])' data.json   # true if it contains all of these
jq '.tags | index("guides")' data.json  # position of a value (null if absent)
jq -c '[min, max]' nums.json            # smallest and largest
jq -c 'min_by(.price).id' items.json    # the element with the smallest .price
jq -c 'group_by(.k) | map({k: .[0].k, n: length})' rows.json  # count by key
# group_by needs sorted input — pipe through sort_by(.k) first

Strings

jq -r '.name | ascii_downcase' data.json     # lowercase (ascii_upcase for upper)
jq -c 'split(",")' <<< '"a,b,c"'       # split into an array
jq 'startswith("he")' <<< '"hello"'    # also: endswith, contains
jq 'test("^[a-z]+[0-9]+$")' <<< '"abc123"'   # regex test (PCRE)
jq -c 'capture("(?<y>[0-9]{4})-(?<m>[0-9]{2})")' <<< '"2026-10-15"'
      # named capture groups → {"y":"2026","m":"10"}
jq -r 'gsub("foo"; "bar")' <<< '"foo foo"'   # replace all (sub = first only)
jq -r 'ltrimstr("--")' <<< '"--hi--"'        # trim a prefix (rtrimstr = suffix)
jq 'tonumber + 8' <<< '"42"'                 # string → number (tostring goes back)
jq '.name | length' data.json                # string length in characters

Numbers

jq '[. + 1, . * 2, . / 4, . % 3, . - 2]' <<< '7'   # + - * / %
jq -c '[sqrt, (. / 4 | floor), (. / 4 | ceil)]' <<< '17'
      # sqrt, round down, round up (also: round, abs)
jq -n 'pow(10; 2)'                        # 100 — power: pow(base; exp)
jq 'log10' <<< '100'                    # 2 — base-10 logarithm (also: log, ln)

Objects

jq -c '.meta | to_entries' data.json        # → [{"key":"lang","value":"en"},...]
jq -c from_entries pairs.json               # back: needs key/value fields
jq -c 'del(.meta.v)' data.json               # delete a field (delpaths for many)
jq -c 'map(.price |= . * 2)' items.json      # |= : update each element in place
jq -c 'walk(if type == "number" then .+10 else . end)' data.json
      # walk: transform every value, recursively
jq -c '. * {"a":9,"b":2}' <<< '{"a":1}'   # merge: right side wins on conflicts
jq -c '. + {"b":2}' <<< '{"a":1}'          # + merges objects too (and adds)

Conditionals & defaults

jq -r 'if . > 3 then "big" else "small" end' <<< '5'
      # if/then/elif/else/end — empty output when no branch matches
jq -c '.a // "default"' <<< '{"a":null}'   # // : use right side if left is null/false
jq -c '.missing? // "fallback"' <<< '{}'   # safe default for absent fields
jq -c '[limit(2; .[])]' <<< '[1,2,3,4]'    # first 2 of a generator
jq -nc '[range(3)]'                          # → [0,1,2]
jq -nc '[range(1; 10; 3)]'                   # → [1,4,7] — range(start; end; step)

Input modes & variables

jq -n '{x: 1}'                    # -n / --null-input: start from null, no stdin
jq -r --arg k name '.[$k]' data.json        # --arg: string variable $k
jq -c --argjson n 5 '{s: (.stars + $n)}' data.json  # --argjson: JSON variable
jq -s -c 'map(.a)' lines.jsonl    # -s / --slurp: read all inputs into one array
jq -R -c . lines.txt              # -R / --raw-input: treat each line as a string
jq -n -c '[inputs.a]' lines.jsonl # inputs: stream the inputs one by one
jq --slurpfile cfg cfg.json -n '$cfg[0]'   # load a whole file into $cfg

Output formats

jq -r '.meta | tojson' data.json     # compact JSON string of a value
jq 'fromjson' <<< '"{\"a\":1}"'     # parse a JSON string back into JSON
jq -r '.[] | [.a,.b] | @csv' rows.json   # CSV rows (quotes + escapes handled)
jq -r '.[] | [.a,.b] | @tsv' rows.json   # TSV rows
jq -r '@base64' <<< '"hello"'        # → aGVsbG8=  (@base64d decodes)
jq -r '@uri' <<< '"a b&c"'          # → a%20b%26c — URL-encode a string
jq -r '@html' <<< '"<b>"'          # → &lt;b&gt; — escape for HTML
jq -r '@sh' <<< "\"it's\""   # → 'it'\''s' — safe for shell
# also: @text (plain string), @json (same as tojson)

Recipes

curl -s https://api.github.com/repos/jqlang/jq | jq '{stars: .stargazers_count, lang: .language}'
      # the classic: curl straight into jq
jq -c 'group_by(.country) | map({country: .[0].country, n: length}) | sort_by(-.n)' users.json
      # count rows per country, most common first
jq -r '.[] | select(.price < 10) | .name' items.json
      # names of everything under 10 — -r prints plain strings
jq '[.. | numbers] | add' data.json      # sum every number in a nested document
jq -c '.[] | {id, price}' items.json     # shorthand: {id: .id, price: .price}
jq -c 'map(select(.in_stock)) | sort_by(.price) | .[0]' items.json
      # cheapest in-stock item

Exit codes & gotchas

jq -e '.ok' data.json     # -e: exit 0 if output is not false/null…
echo $?                   # …exit 1 on false/null, 4 on empty output
# exit codes: 0 ok · 1 false/null with -e · 2 usage error · 3 compile error
#             4 no output · 5 unknown system error
set -o pipefail           # in scripts: catch jq failures inside a pipeline
jq -c '.a' <<< '{}'        # null — not an error; add ? to be explicit
# .foo on an array iterates? no — use .[] first: '.[] | .foo'