jq

command-line JSON processor · cheatsheet
$ jq --help
— identity & navigation

Identity & fields

.identity — pass input through unchanged
.foofield access on object
{"foo":"bar"} → "bar"
.foo.barnested field access
.["foo"]bracket notation (for special chars / vars)
.foo?optional operator — suppress errors if missing
.foo // "default"alternative operator (use if null or false)

Arrays

.[0]first element
.[-1]last element
.[2:5]slice — index 2 up to (not incl.) 5
.[]explode array — emit each element separately
.[1:]slice from index 1 to end
lengthlength of array, string, or object
— transformation

Pipe & construction

. | .foopipe — chain filters
{a: .x, b: .y}construct new object
{(.key): .val}computed key in object construction
[.[] | .name]collect into array
., .foocomma — produce multiple outputs
emptyproduce no output (useful in conditionals)

map & select

map(.x)apply filter to each element → array
equivalent to [.[] | .x]
map_values(.x)apply to values of object or array
select(cond)keep element only if condition is true
map(select(.n > 2))filter array by condition
to_entriesobject → [{key, value}]
from_entries[{key, value}] → object
with_entries(f)to_entries | map(f) | from_entries

Reduce & aggregation

addsum array / concatenate strings or arrays
anytrue if any element is truthy
alltrue if all elements are truthy
any(cond)any element satisfies condition
all(cond)all elements satisfy condition
min_by(.x) / max_by(.x)min/max element by key
group_by(.x)group elements by key → array of arrays
unique / unique_by(.x)deduplicate array
sort / sort_by(.x)sort array
flatten / flatten(n)flatten nested arrays (to depth n)
reduce .[] as $x (0; .+$x)reduce with accumulator
reduce EXPR as $var (INIT; UPDATE)

String operations

"\(.foo) bar"string interpolation
split(",")split string → array
join(",")join array of strings
ltrimstr("x")trim prefix if present
rtrimstr("x")trim suffix if present
startswith("x")test prefix
endswith("x")test suffix
ascii_downcaselowercase string
test("regex")test string against regex → bool
match("regex")match object with captures
capture("(?<n>...)")named captures → object
gsub("x";"y")global substitution
— types & logic

Types & conversion

typereturn type as string
"null" "boolean" "number" "string" "array" "object"
arraysselect only array values
objectsselect only object values
stringsselect only string values
numbersselect only number values
nullsselect null values
tostringconvert to string (JSON-encode if not string)
tonumberparse string as number
tojsonencode value as JSON string
fromjsonparse JSON string → value
keyssorted array of object keys
keys_unsortedobject keys, insertion order
valuesarray of object values
has("key")test if key/index exists
in(obj)test if input is a key in obj
contains(val)recursive containment check

Conditionals & variables

if A then B else C endconditional (else is required)
if A then B elif C then D else E endchained conditions
notboolean negation
== != < <= > >=comparison operators
and orboolean operators
.x as $v | ...bind value to variable
label-breaklabel $out | ... , break $out
try EXP catch EXPcatch errors (. = error message in catch)
error("msg")raise an error
def f(x): ...;define a function
def addtwo: . + 2; 5 | addtwo → 7
— paths & advanced

Path expressions

path(.a.b)path expression → ["a","b"]
getpath(["a","b"])get value at path array
setpath(["a"]; val)set value at path
delpaths([["a","b"]])delete paths
del(.foo)delete a key from object or element from array
[paths]all paths in the input
[leaf_paths]paths to leaf (scalar) values only
.. | .foo?recursive descent — search all levels

Update operators

.foo |= . + 1update field in place
.foo += 1arithmetic update shorthand
.foo -= 1subtract update
.a |= del(.b)delete nested key
+ { "x": 1 }merge object (right wins on conflict)
- ["x"]array subtraction (remove elements)
.[] |= select(. > 2)filter array in place
— cli flags

Useful CLI flags

-r / --raw-output print strings without JSON quotes $ jq -r '.Name'
-c / --compact-output output on single line (no pretty-print) $ jq -c '.'
-s / --slurp read all inputs into one array $ cat *.json | jq -s '.'
-n / --null-input no input — use null as input (good for constructing JSON) $ jq -n '{a:1}'
-R / --raw-input read each line as a raw string
--arg name val bind shell string to jq variable $name $ jq --arg k "mykey" '.[$k]'
--argjson name val bind JSON value to jq variable $name $ jq --argjson n 42 'select(. > $n)'
--slurpfile name f bind contents of file to $name (as array)
-e / --exit-status exit 1 if last output is false/null (useful in scripts)
-f file read filter from file instead of arg $ jq -f filter.jq data.json
— container inspect recipes

podman / docker inspect recipes

explore top-level keys of first result
$ podman inspect mycontainer | jq '.[0] | keys'
get container IP address
$ podman inspect mycontainer | jq '.[0].NetworkSettings.IPAddress'
list all env vars
$ podman inspect mycontainer | jq '.[0].Config.Env[]'
find a specific env var (e.g. PATH)
$ podman inspect mycontainer | jq '.[0].Config.Env[] | select(startswith("PATH"))'
list all mount points
$ podman inspect mycontainer | jq '.[0].Mounts[] | {src: .Source, dst: .Destination, rw: .RW}'
list all exposed ports
$ podman inspect mycontainer | jq '.[0].NetworkSettings.Ports | keys'
extract name + status for all containers (inspect multiple)
$ podman inspect $(podman ps -aq) | jq '.[] | {name: .Name, status: .State.Status}'
explore image layers
$ podman image inspect myimage | jq '.[0].RootFS.Layers'
recursively find any field named "Image" anywhere in the structure
$ podman inspect mycontainer | jq '.. | objects | .Image? // empty'
same thing — but print the path to every field named "Image"
$ podman inspect mycontainer | jq '[path(.. | .Image?)] '