Tutorial jq JSON CLI Data Processing Filtering Shell Terminal Developer Tools Cheat Sheet

Free jq Commands Cheat Sheet Online — 120+ JSON Processor Filters & Command Reference

· 20 min read

jq is the JSON sculptor's chisel — it carves raw JSON data into precisely the shape you need, one filter at a time. From simple field access to recursive tree traversal, object construction to complex data pipelines, jq has been the universal JSON processor since 2012. Our free interactive jq Commands Cheat Sheet gives you instant access to 120 filters and patterns across 10 categories, with real-time search, one-click copy, and a JSON Quarry aesthetic inspired by stone carving, sculptor's workshops, and mineral accents. No signup. No server. 100% client-side.

Why jq Is the Universal JSON Sculptor

Every developer who works with APIs, configuration files, log analysis, or data pipelines eventually discovers jq — and wonders how they ever lived without it. jq is to JSON what sed/awk are to text: a domain-specific language that transforms structured data with remarkable concision. Instead of writing a Python script to extract one field from a JSON response, you pipe through jq '.field'. Instead of looping through arrays, you write jq 'map(select(.active))'. jq's filter language is functional, composable, and astonishingly expressive — a single line of jq often replaces dozens of lines of general-purpose code.

The jq ecosystem has matured into a complete data processing toolkit. Built-in functions cover math, string manipulation, regex matching, date handling, type conversion, and recursion. Module support (include/import) enables reusable filter libraries. The streaming parser (--stream) handles multi-gigabyte JSON files in constant memory. Variables, user-defined functions, and the reduce/foreach iterators make jq Turing-complete. Our cheat sheet organizes jq's entire filter language into 10 focused categories with every operator, built-in, and practical example you need — from jq '.' (the identity filter that pretty-prints JSON) to jq 'recurse(.children[]) | select(.type == "file")' (recursive tree search) to jq --stream '.' huge.json (incremental parsing for files too large to fit in memory).

Basic Filters & Output — The Foundation

Every jq journey starts with basic filters. Our Basic Filters & Output category covers: jq '.' (identity filter — pretty-prints JSON with syntax coloring, the most fundamental jq command), jq '.field' (access a specific object field — returns null if the field doesn't exist, no crash), jq '.a.b.c' (chained field access for nested objects — each dot descends one level deeper, any missing key returns null), jq '.[]' (array/object iterator — unwraps one level, outputting each element for arrays or each value for objects), jq '.[0]' (array index access — zero-indexed, negative indices count from the end), jq '.[-1]' (last element via negative indexing — cleaner than length-based access), jq '.[2:5]' (array slicing — works like Python slicing with optional start/end), jq 'keys' (get all object keys as a sorted array — use keys_unsorted for insertion order), jq -r '.' (raw output mode — strips JSON quotes from strings, essential for shell pipelines), jq -c '.' (compact output — one JSON value per line, perfect for NDJSON streaming), jq 'length' (count elements — works on arrays, strings, objects, and numbers), and jq '.[] | {name, age}' (object projection — {name, age} is shorthand for {name: .name, age: .age}).

Object & Array Construction — Building New Structures

jq doesn't just extract data — it builds entirely new JSON structures. Our Object & Array Construction category covers: jq '{fullname: (.first + " " + .last)}' (construct a new object with computed values — key expressions in parentheses), jq '{name, email}' (shorthand object construction — {name} is equivalent to {name: .name}, pick multiple fields with minimal syntax), jq '[.a, .b, .c]' (build a new array from specific fields — each expression inside [] becomes an element), jq '[.[] | {name, score}]' (build a new array by iterating and transforming — pipe each element through a filter, wrapped in []), jq '{payload: ., meta: {ts: now}}' (nested object construction — wrap data with metadata, common API response pattern), jq '. + {extra: "val"}' (merge two objects with + — right-hand keys override left-hand on conflict), jq '[.]' (wrap any value in a single-element array — for when downstream tools expect an array), jq 'add' (sum for numbers, concatenation for strings, merge for objects — the universal aggregator), jq 'del(.field1, .field2)' (delete one or more fields — great for sanitizing sensitive output), jq 'with_entries(.key |= ascii_upcase)' (transform object keys via with_entries — to_entries | map(f) | from_entries pattern), jq '{} + .' (identity merge — ensures output is always an object), and jq '{($key): .value}' (dynamic key construction using string interpolation — key name comes from a variable).

Filtering & Selection — Finding What You Need

Filtering is where jq truly shines — selecting precisely the data you need from large JSON documents. Our Filtering & Selection category covers: jq 'select(.price > 100)' (filter by boolean condition — select() passes through input only when the condition is truthy), jq 'map(select(.active))' (filter array elements — map(select(COND)) is the canonical array filtering pattern), jq '.[] | select(.role == "admin")' (filter after unwrapping — iterate then filter, allows post-filter transformations), jq 'has("email")' (check if an object has a given key — returns true/false, null-safe), jq '.[] | select(.tags | contains(["urgent"]))' (filter by array containment — contains() works on arrays, strings, and objects), jq '.[] | select(.name | test("^A"))' (regex filter — test() supports full PCRE regex with optional flags), jq '.[] | select(.age > 18 and .age < 65)' (compound conditions with and/or — chain multiple boolean expressions), jq '.[] | select(.items | length > 0)' (filter by array length — length gives 0 for empty arrays), jq '.[] | select(.address != null)' (filter for non-null fields — both missing keys and null values return null), jq 'first(.[] | select(.status == "ready"))' (find the first matching element — efficient, short-circuits after first match), and jq '.[] | select(.name | IN("Alice", "Bob"))' (filter by value membership — IN() checks if a value appears in a set of alternatives, jq 1.6+).

Transformation & Mapping — Reshaping Data

Transformation operators reshape JSON into entirely new forms. Our Transformation & Mapping category covers: jq 'map(.price * 1.1)' (map transform — apply a transformation to every array element, the primary array operation), jq 'map_values(. * 100)' (transform object values while preserving keys — map for arrays, map_values for objects), jq 'to_entries' (convert object to array of {key, value} pairs — enables key-based operations), jq 'from_entries' (convert array of {key, value} pairs back to an object — the inverse of to_entries), jq 'with_entries(.value |= . * 2)' (transform both keys and values — with_entries(f) = to_entries | map(f) | from_entries), jq 'map({(.id): .name}) | add' (array to lookup object — map each item to a single-key object, then merge all with add), jq '.[] |= . + {updated: now}' (update operator |= — modify each array element in-place, combining old and new via +), jq '. as $in | [$in.a, $in.b]' (deconstruct input into variables for reorganization — bind . to a variable for repeated access), jq 'map(. * .)' (square all numbers — map() plus arithmetic for transforming numeric arrays), jq 'tojson' (convert any jq value to a JSON-encoded string — for embedding JSON inside string fields), and jq 'fromjson' (parse a JSON-encoded string back to jq values — the inverse of tojson).

String & Number Operations — Working with Values

jq has a full suite of string and number manipulation built-ins. Our String & Number Operations category covers: jq '.name | length' (string length in characters — also works on arrays and objects), jq '.email | split("@")[1]' (split a string by delimiter and index the result — common for extracting domains), jq '.first + " " + .last' (string concatenation with + — use string interpolation "\\(expr)" for mixed types), jq '.name | ascii_downcase' (lowercase conversion — ascii_upcase for uppercase, ASCII only), jq '.text | gsub(" "; "_")' (global regex substitution — gsub(regex; replacement) replaces every match, sub() replaces only the first), jq '.price | floor' (floor — round down, related: ceil, round, trunc), jq '.score | tonumber' (string to number conversion — use tonumber? for null on error instead of crashing), jq '.id | tostring' (number to string — the universal string conversion operator), jq '[.[] | .price] | add / length' (average calculation — collect values, sum, divide by count), jq '.amount * 100 | round / 100' (round to 2 decimal places — multiply, round to integer, divide back), jq '.text | test("error"; "i")' (case-insensitive regex test — "i" flag for case-insensitive, "m" for multiline, "g" for global), and jq '.data | @base64d | fromjson' (decode base64-encoded JSON — two-step: decode base64 then parse JSON).

Array Operations — Sorting, Grouping, Deduplicating

jq's array operations rival Python's itertools and JavaScript's lodash. Our Array Operations category covers: jq 'sort' (sort comparable values — for objects by field, use sort_by), jq 'sort_by(.price)' (sort array of objects by a specific field — stable sort, equal values preserve original order), jq 'unique' (remove duplicate elements — keeps first occurrence of each value), jq 'unique_by(.id)' (deduplicate array of objects by a specific field — keeps first object for each unique .id), jq 'reverse' (reverse element order — combine with sort_by for descending sort), jq 'group_by(.category)' (group elements by a field into sub-arrays — result is array of arrays, each with same category), jq 'flatten' (flatten nested arrays by one level — use flatten(N) for N levels deep), jq 'flatten(2)' (flatten exactly N levels — flatten(99) for deep flattening of unknown depth), jq '{names: [.[].name], ages: [.[].age]}' (extract multiple arrays — collect different fields into named arrays), jq 'indices("needle")' (find all indices where a value appears — for arrays and strings), jq '.[:3] + .[-3:]' (combine array slices — first 3 plus last 3 elements), and jq '{min, max, sum:add, avg:(add/length), count:length}' (compute descriptive statistics — all five stats collected in a single object).

Conditionals & Logic — Decision-Making in Filters

jq's conditional expressions bring program logic into data pipelines. Our Conditionals & Logic category covers: jq 'if . > 0 then "positive" else "negative" end' (if-then-else conditional — else is mandatory in jq, elif is optional for multi-branch), jq 'if .score >= 90 then "A" elif .score >= 80 then "B" else "F" end' (multi-branch conditional — each condition checked in order, first match wins), jq '.nickname // .name' (alternative operator // — returns left if truthy, otherwise right, perfect for defaults and fallbacks), jq '[.[] | .score > 60] | all' (check if a condition holds for every element — all returns true if every value is truthy), jq 'any(.score < 60)' (check if any element matches — any returns true if at least one value is truthy), jq 'not' (logical NOT — invert a boolean, true→false, false→true, null→true), jq 'empty' (produce nothing — use to conditionally suppress output, like a filter that outputs zero values), jq '.items // []' (null-safe array access — returns .items if it exists, otherwise empty array, preventing downstream errors), jq '(.a // 0) + (.b // 0) + (.c // 0)' (null-safe arithmetic — treat missing or null fields as 0 for safe summation), jq 'true, false' (boolean literals — true and false are first-class jq values, comma produces multiple outputs), jq '{name} + (if .extra then {extra} else {} end)' (conditional object construction — add a key only when it exists, merge with {} when absent), and jq 'select(.tags | type == "array" and length > 0)' (type-checking combined with logic — verify field is an array AND non-empty before processing).

Advanced Paths & Recursion — Deep Tree Traversal

jq's recursive capabilities let you traverse arbitrarily deep JSON trees. Our Advanced Paths & Recursion category covers: jq '..' (recursive descent — produces every value in the JSON tree, from root to leaves), jq '.. | .name?' (recursive descent with optional field access — find ALL .name fields at any depth, ? suppresses errors on missing keys), jq 'recurse(.children[])' (controlled recursion — start at root, recursively follow .children[] arrays), jq 'recurse(.children[]) | select(.type == "file")' (recursive search with filter — find all nodes of a specific type anywhere in a deeply nested tree), jq 'paths' (get all paths to every value — each path is an array of keys/indices, useful for schema discovery), jq 'paths | join(".")' (dot-notation path strings — convert path arrays to human-readable key paths), jq 'getpath(["a","b",0])' (access nested value via a path array — equivalent to .a.b[0] but the path can be dynamically computed), jq 'setpath(["a","b"]; "new")' (set a value at a given path, creating intermediates — immutable, returns new object), jq 'delpaths([["a","b"], ["c"]])' (delete values at multiple paths — cleaner than multiple del() calls), jq 'walk(if type == "string" then trim else . end)' (walk transforms every leaf value — bottom-up recursive transformation), jq 'leaf_paths' (paths to all leaf/scalar values — excludes paths to non-leaf nodes like objects and arrays), and jq '[.. | select(type == "number")]' (find all numbers anywhere in a complex JSON tree — recursive descent with type-based filtering).

Variables, Functions & Modules — Composable Filter Logic

jq supports variables, user-defined functions, recursion, and modules for building reusable filter libraries. Our Variables, Functions & Modules category covers: jq '. as $root | $root.users | map(.name)' (bind input to a variable with 'as $name' — variables start with $ and let you reference earlier values later in the pipeline), jq 'def double: . * 2; map(double)' (define a reusable function with 'def name: body;' — functions can reference . and take parameters), jq 'def greet($name): "Hello \\($name)"; greet("World")' (define a function with parameters — arguments use $ prefix, string interpolation with \\(expr)), jq 'reduce .[] as $item (0; . + $item)' (reduce/fold — accumulate array elements into a single value, the classic sum pattern), jq 'reduce .[] as $item ({}; .[$item.key] = $item.value)' (build an object from an array via reduce — powerful for custom aggregation), jq 'foreach .[] as $item (0; . + $item; .)' (foreach — like reduce but outputs intermediate values, running sum at each step), jq 'include "utils"; my_function' (include a module — all definitions from the module file available directly without namespace), jq 'import "math" as math; math::pow(2; 10)' (import a module with namespace — prevents name collisions between modules), jq 'def fact: if . <= 1 then 1 else . * (. - 1 | fact) end; fact' (recursive function definition — jq supports functions calling themselves), jq '{name} + (.addr // {})' (conditional merge with default — add address fields if they exist, otherwise add nothing), jq '. as $in | {sum: ($in.a + $in.b + $in.c)}' (reference input multiple times via variable — cleaner than repeating field access), and jq 'def pick($k): {($k): .[$k]}; pick("name")' (generic function with dynamic key — function parameter becomes an object key via interpolation).

Formatting & CLI Options — jq in Production

jq's CLI flags control input/output modes, variable passing, and performance characteristics. Our Formatting & CLI Options category covers: jq -s '.' (slurp mode — read ALL input JSON values into a single array, essential for NDJSON to JSON array conversion), jq -S '.' (sort keys in output alphabetically — makes JSON deterministic, great for diffing and git), jq -R '.' (read input as raw strings, not JSON — each line becomes a string for processing), jq --arg name value '.' (pass a string variable from the shell into jq — available as $name, always a string), jq --argjson data '{"a":1}' '.' (pass a JSON value from the shell — parsed as JSON, can be objects, arrays, numbers, booleans), jq -n '.' (null input mode — don't read from stdin, essential for building JSON from CLI arguments), jq -f script.jq (read the jq filter from a file — essential for complex multi-line filters that would be unwieldy on the CLI), jq -L /path/to/modules '.' (add a directory to the module search path — jq looks here for .jq files when using include/import), jq --slurpfile users users.json '.' (slurp an entire file into a variable as an array — unlike --argjson which takes one value), jq --rawfile content file.txt '.' (read an entire file into a string variable — multiline files as single string, unlike --arg), jq -e '.' (set exit code based on output — exit 0 for non-null/non-false, exit 1 for null/false or no output, essential for shell conditionals), and jq --stream '.' (streaming mode — parse JSON incrementally without loading into memory, for files too large to fit in RAM).

The JSON Quarry — Aesthetic Design

jq carves JSON like a sculptor working raw stone — shaping, chiseling, transforming unrefined data into polished structures. Our jq Commands Cheat Sheet embraces The JSON Quarry aesthetic: a deep quarry stone background (#18181c) with chisel-mark grid lines — horizontal cuts at 38%, 67%, and 85%, vertical cuts at 28%, 55%, and 73% — creating the visual impression of a sculptor's workshop where data is carved and shaped. A workshop lamp glow bar runs along the top edge with a warm copper-to-pyrite-to-gold gradient, flickering gently like a studio lamp in the quarry breeze.

Twenty-five floating stone dust motes — tiny glowing dots in mineral tones — drift upward through the workshop air, cycling through all ten mineral category colors: quartz white, copper ore, iron pyrite, malachite green, azurite blue, cinnabar red, serpentine green, rhodochrosite pink, galena gray, and native gold. A diamond chisel mark (◆) gleams after the title with a scale-pulse animation — the tool awaiting its next cut. Cinzel provides monumental display headings — carved inscription proportions with classical weight. EB Garamond delivers refined, scholarly body text with italic grace. JetBrains Mono serves all code snippets and filter expressions with monospace precision. The mineral palette maps to jq's domains: Quartz White (#c8c0b0, Basic Filters — the raw material), Copper Ore (#cc9966, Object & Array Construction — molding form), Iron Pyrite (#ddaa44, Filtering & Selection — finding the gold), Malachite Green (#55aa88, Transformation & Mapping — alchemical change), Azurite Blue (#5588bb, String & Number Operations — deep processing), Cinnabar Red (#cc6655, Array Operations — cutting and sorting), Serpentine Green (#77aa55, Conditionals — branching veins), Rhodochrosite Pink (#cc8899, Advanced Paths — exploring the vein), Galena Gray (#889999, Variables & Functions — structural metal), and Native Gold (#ddbb55, Formatting & CLI Options — the finished product). Cards feature mineral-colored top borders (3px) with a rotating diamond facet indicator — a chisel-cut crystal that pulses with inner light. Cards are textured like carved stone tablets with subtle linear-gradient highlights, and hover effects reveal deeper shadows and a golden gleam. This is not another dark mode theme; it's a deliberate, crafted space that makes JSON processing feel like working in a master sculptor's atelier.

How This Cheat Sheet Fits Into Your Workflow

The jq Commands Cheat Sheet is part of the DevToolkit suite of free developer reference tools. It complements our curl Commands Cheat Sheet (fetching the JSON that jq processes — curl pulls data from APIs, jq transforms it), our Linux Commands Cheat Sheet (the terminal environment where jq runs), our Bash Scripting Advanced Patterns Cheat Sheet (automating jq pipelines in shell scripts), our JSON Formatter (complementary browser-based JSON tool for quick formatting), and our Web APIs Cheat Sheet (the APIs that produce the JSON jq processes). Together, jq, the Linux terminal, and your API toolkit form the complete data processing pipeline — fetch JSON with curl, transform it with jq, and pipe the result to the next tool. This is the command line at its most powerful.

The workflow is simple: press Ctrl+K to focus the search bar, type what you need (a filter pattern like "select", a function like "map", a concept like "recursive"), and the matching entries appear instantly. Click any card to copy its jq filter to your clipboard — the toast notification prefixes every copy with "[jq]" as a subtle reminder. Filter by category to narrow the view — jump directly to "Filtering & Selection" to review the complete select() family, or "Advanced Paths & Recursion" to master tree traversal. Everything runs in your browser — no server requests, no signup, no tracking. Bookmark it, keep it open while writing data pipelines, and stop searching through `man jq` for the filter syntax you half-remember.


Related Cheat Sheets