jq Cheat Sheet
jq is a lightweight command-line JSON processor.
Basic Usage
Section titled “Basic Usage”# Pretty printcat file.json | jq '.'jq '.' file.json
# Compact output (no pretty print)jq -c '.' file.json
# Raw output (no quotes on strings)jq -r '.name' file.json
# Read from stringecho '{"name":"alice"}' | jq '.name'| Flag | Description |
|---|---|
-r | Raw output (no quotes) |
-c | Compact output (one line) |
-s | Slurp: read all inputs into array |
-n | Null input (don’t read stdin) |
-e | Exit with error if output is false/null |
-S | Sort object keys |
--arg name val | Pass string variable |
--argjson name val | Pass JSON variable |
Navigation
Section titled “Navigation”Object Access
Section titled “Object Access”# Sample: {"name": "alice", "age": 30, "address": {"city": "NYC"}}
jq '.name' # "alice"jq '.address.city' # "NYC"jq '.missing' # nulljq '.missing // "default"' # "default"
# Optional access (no error if null)jq '.foo?.bar?' # null (instead of error)
# Bracket notationjq '.["name"]' # "alice"jq '.["key-with-dash"]' # Works with special charsArray Access
Section titled “Array Access”# Sample: [10, 20, 30, 40, 50]
jq '.[0]' # 10jq '.[-1]' # 50 (last element)jq '.[1:3]' # [20, 30]jq '.[:2]' # [10, 20]jq '.[-2:]' # [40, 50]jq '.[2:]' # [30, 40, 50]Iteration
Section titled “Iteration”# Sample: [{"name": "a"}, {"name": "b"}]
jq '.[]' # Iterate: {"name":"a"} then {"name":"b"}jq '.[].name' # Iterate: "a" then "b"jq '.[] | .name' # Same as above
# Sample: {"a": 1, "b": 2}jq '.[]' # Iterate values: 1 then 2jq 'keys' # ["a", "b"]jq 'keys[]' # "a" then "b"Operators
Section titled “Operators”jq '.users | .[] | .name'jq '.users[].name' # Equivalent shorthandComma (Multiple Outputs)
Section titled “Comma (Multiple Outputs)”jq '.name, .age' # Output bothjq '{name, age}' # Build object with bothParentheses (Grouping)
Section titled “Parentheses (Grouping)”jq '(.a + .b) * 2'Constructing Values
Section titled “Constructing Values”Objects
Section titled “Objects”# Build new objectjq '{name: .user, count: .total}'jq '{name, age}' # Shorthand: {name: .name, age: .age}jq '{(.key): .value}' # Dynamic key
# Add/update fieldsjq '. + {newfield: "value"}'jq '.name = "bob"'jq '.users[0].name = "bob"'
# Remove fieldsjq 'del(.unwanted)'jq 'del(.users[0])'Arrays
Section titled “Arrays”# Build arrayjq '[.items[].name]' # Collect into arrayjq '[., .]' # Duplicate input
# Add to arrayjq '. + ["new"]'jq '. += ["new"]'
# Concatenate arraysjq '.arr1 + .arr2'Filtering
Section titled “Filtering”Select
Section titled “Select”# Filter array elementsjq '.[] | select(.age > 21)'jq '.[] | select(.active == true)'jq '.[] | select(.name | contains("ali"))'jq '.[] | select(.tags | index("admin"))'
# Multiple conditionsjq '.[] | select(.age > 21 and .active)'jq '.[] | select(.role == "admin" or .role == "mod")'
# Negationjq '.[] | select(.deleted | not)'# Transform each elementjq 'map(.name)' # [{"name":"a"},...] → ["a",...]jq 'map(. * 2)' # [1,2,3] → [2,4,6]jq 'map(select(.active))' # Filter with mapjq 'map({name, email})' # Project fields
# map_values for objectsjq 'map_values(. + 1)' # {"a":1,"b":2} → {"a":2,"b":3}Group & Sort
Section titled “Group & Sort”jq 'group_by(.category)' # Group into sub-arraysjq 'sort_by(.date)' # Sort array of objectsjq 'sort_by(.date) | reverse' # Sort descendingjq 'sort' # Sort array of primitivesjq 'unique' # Remove duplicatesjq 'unique_by(.id)' # Unique by fieldString Operations
Section titled “String Operations”jq '.name | length' # String lengthjq '.name | ascii_downcase' # Lowercasejq '.name | ascii_upcase' # Uppercasejq '.name | ltrimstr("Mr. ")' # Remove prefixjq '.name | rtrimstr(" Jr.")' # Remove suffixjq '.name | split(" ")' # Split to arrayjq '.parts | join("-")' # Join arrayjq '"\(.first) \(.last)"' # String interpolationjq '.name | startswith("A")' # Boolean checkjq '.name | endswith("son")' # Boolean checkjq '.name | contains("ali")' # Boolean checkjq '.name | test("^[A-Z]")' # Regex matchjq '.name | capture("(?<first>\w+)")' # Regex capturejq '.name | sub("old"; "new")' # Replace firstjq '.name | gsub("old"; "new")' # Replace allNumeric Operations
Section titled “Numeric Operations”jq '.price * 1.1' # Arithmeticjq '.values | add' # Sum arrayjq '.values | add / length' # Averagejq '.values | min' # Minimumjq '.values | max' # Maximumjq '.value | floor' # Round downjq '.value | ceil' # Round upjq '.value | round' # Round nearestjq 'range(5)' # 0,1,2,3,4jq '[range(5)]' # [0,1,2,3,4]Array Operations
Section titled “Array Operations”jq 'length' # Array/string/object lengthjq 'first' # First element (.[0])jq 'last' # Last element (.[-1])jq 'nth(2)' # Third element (.[2])jq 'flatten' # Flatten nested arraysjq 'flatten(1)' # Flatten one leveljq 'reverse' # Reverse arrayjq 'indices("x")' # Find all indices of valuejq 'inside([1,2,3])' # Check if subsetjq 'contains([1,2])' # Check if containsjq '. - ["a","b"]' # Remove elementsjq 'limit(3; .[])' # First 3 elementsjq '[limit(3; .[])]' # As arrayjq 'first(.[]; . > 5)' # First matchingConditionals
Section titled “Conditionals”# if-then-elsejq 'if .age >= 18 then "adult" else "minor" end'
# Alternative operator (default value)jq '.name // "unknown"'jq '.items[0] // empty' # No output if null
# Error handlingjq 'try .foo.bar catch "error"'jq '.items[]? | .name' # Suppress errorsReduce & Recursion
Section titled “Reduce & Recursion”# Reduce (fold)jq 'reduce .[] as $x (0; . + $x)' # Sum
# Recursive descentjq '.. | numbers' # All numbers at any depthjq '.. | strings' # All strings at any depthjq '.. | .name? // empty' # All "name" values
# Walk (transform recursively)jq 'walk(if type == "string" then ascii_upcase else . end)'Variables
Section titled “Variables”# Define variablejq '.user as $u | .posts[] | {title, author: $u}'
# From command linejq --arg name "alice" '.users[] | select(.name == $name)'jq --argjson id 123 '.users[] | select(.id == $id)'
# Multiple variablesjq --arg a "x" --arg b "y" '{first: $a, second: $b}'Multiple Inputs
Section titled “Multiple Inputs”# Slurp into arrayjq -s '.' file1.json file2.json # Combine into arrayjq -s 'add' file1.json file2.json # Merge objects
# Process each filejq '.name' file1.json file2.json # Output from each
# Input from arrayjq '.[]' <<< '[1,2,3]' # Stream itemsPractical Examples
Section titled “Practical Examples”Extract nested values
Section titled “Extract nested values”jq '.data.users[].profile.email'Filter and project
Section titled “Filter and project”jq '[.users[] | select(.active) | {name, email}]'Count items
Section titled “Count items”jq '[.items[] | select(.status == "done")] | length'Group and count
Section titled “Group and count”jq 'group_by(.category) | map({category: .[0].category, count: length})'Flatten nested structure
Section titled “Flatten nested structure”jq '[.departments[].employees[].name]'Merge objects
Section titled “Merge objects”jq -s '.[0] * .[1]' defaults.json config.jsonConvert CSV-like to JSON
Section titled “Convert CSV-like to JSON”jq -R -s 'split("") | map(split(",")) | map({name: .[0], value: .[1]})'Update deeply nested value
Section titled “Update deeply nested value”jq '.config.database.host = "newhost"'Add field to all array elements
Section titled “Add field to all array elements”jq '.users[] |= . + {processed: true}'Remove null values
Section titled “Remove null values”jq 'del(..|nulls)'jq 'with_entries(select(.value != null))'Convert object to array of key-value pairs
Section titled “Convert object to array of key-value pairs”jq 'to_entries' # [{key, value}, ...]jq 'to_entries | map("\(.key)=\(.value)") | .[]'Construct object from arrays
Section titled “Construct object from arrays”jq -n '{names: $ARGS.positional}' --args alice bob charliePretty print with sorted keys
Section titled “Pretty print with sorted keys”jq -S '.'Get unique values from nested arrays
Section titled “Get unique values from nested arrays”jq '[.items[].tags[]] | unique'Sum values by group
Section titled “Sum values by group”jq 'group_by(.category) | map({category: .[0].category, total: map(.amount) | add})'See Also
Section titled “See Also”- Shell — Scripting patterns for pipelines and data processing
- CLI Pipelines: Keeping Data in the Stream
- HTTP
- Kubernetes
- Regex
- Unix CLI