elefcode
← All cheat sheets

Tools

jq Cheat Sheet — Filter and Transform JSON on the Command Line

jq is the command-line tool for slicing JSON — API responses, logs, and config files. These are the filters that cover most real-world use.

Put it into practice with the matching tool.

Format and explore JSON →

Advertisement

Basics

jq '.' file.jsonPretty-print JSON
curl -s url | jq '.'Pretty-print an API response
.nameGet a field
.user.address.cityGet a nested field
.["first-name"]Get a field with special characters
.name?Suppress errors if the input is not an object

Arrays

.[0] / .[-1]First / last element
.[2:5]Slice
.[]Iterate — output each element separately
.items[].idGet one field from every element
lengthLength of an array, object, or string
[.[] | .id]Collect results back into an array

Filtering and mapping

map(.price * 2)Transform every element
map(select(.active))Keep elements where a condition is true
.[] | select(.age > 30)Filter while iterating
sort_by(.date) / reverseSort by a field / reverse an array
group_by(.type)Group into arrays by a field
unique_by(.id)Remove duplicates by a field
first(.[] | select(.ok))First matching element
addSum numbers or concatenate arrays and strings

Building output

{id, name}New object with selected fields
{user: .name, n: (.items | length)}New object with computed values
"\(.first) \(.last)"String interpolation
keys / to_entriesObject keys / list of {key, value} pairs
.a // "default"Fallback when a value is null or missing
del(.password)Remove a field
.count += 1Update a value in place

Command-line options

-rRaw output — strings without quotes
-cCompact output, one JSON value per line
-sSlurp all inputs into one array
--arg name "$VAR"Pass a shell variable as $name
-eSet the exit status from the last output (useful in scripts)
.[] | @csvFormat an array as a CSV row (also @tsv, @base64, @uri)

Related guides

More cheat sheets