Skip to content

jq

120 commands

A lightweight command-line JSON processor: filter, transform and pretty-print JSON from APIs, logs and tool output.

  • JSON
  • parsing
  • data

Install jq

sudo apt install jq

Basic Usage2

jq '.' file.json

Pretty prints the entire JSON content to standard output with syntax highlighting.

Link
jq -c '.' file.json

Compacts the JSON output into a single line per object to save space.

Link

Field Access4

jq '.key' file.json

Extracts the value of a specific key from the root object.

Link
jq '.foo.bar' file.json

Accesses a nested key using dot notation.

Link
jq '."complex-key"' file.json

Accesses keys containing special characters or hyphens using quotes.

Link
jq '.foo?' file.json

Suppress errors if the field does not exist (null safety).

Link

Array Operations5

jq '.[0]' file.json

Extracts the first element of an array.

Link
jq '.[-1]' file.json

Extracts the last element of an array.

Link
jq '.[1:4]' file.json

Slices an array, returning elements from index 1 up to (but not including) 4.

Link
jq '.[]' file.json

Iterates over an array or object values, unpacking them into a stream.

Link
jq 'length' file.json

Returns the length of a string, array, or object.

Link

Object Construction2

jq '{new_key: .old_key}' file.json

Constructs a new object with renamed or selected fields.

Link
jq '[.a, .b]' file.json

Constructs a new array containing selected values.

Link

Input/Output Control1

jq -r '.key' file.json

Outputs raw strings without quotes, useful for shell piping.

Link

Structure Analysis2

jq 'keys' file.json

Returns an array of keys in the object, sorted alphabetically.

Link
jq 'keys_unsorted' file.json

Returns keys in the order they appear in the source JSON.

Link

Math & Logic2

jq '.price * 1.2' file.json

Performs arithmetic operations on numeric fields.

Link
jq '.a + .b' file.json

Adds numbers or concatenates strings depending on type.

Link

Transformation1

jq 'map(.id)' file.json

Transforms an array by applying a filter to every element.

Link

Filtering3

jq 'select(.id > 100)' file.json

Filters output, keeping only elements where the condition is true.

Link
jq 'select(.status == "active")' file.json

Filters stream for objects matching a specific string value.

Link
jq 'select(.error != null)' file.json

Selects objects where a specific field is not null.

Link

Logical Operators2

jq 'select(.a and .b)' file.json

Uses boolean AND logic to require multiple conditions.

Link
jq 'select(.a or .b)' file.json

Uses boolean OR logic to allow alternative conditions.

Link

String Manipulation4

jq 'split(",")' file.json

Splits a string into an array based on a delimiter.

Link
jq 'join(", ")' file.json

Joins an array of strings into a single string with a separator.

Link
jq 'ascii_downcase' file.json

Converts string input to lowercase.

Link
jq 'contains("str")' file.json

Checks if a string contains a specific substring.

Link

Regular Expressions3

jq 'test("regex")' file.json

Tests if a string matches a regular expression pattern.

Link
jq 'match("regex")' file.json

Returns detailed match object including captures and offsets.

Link
jq 'capture("regex")' file.json

Captures named groups from a regex into a JSON object.

Link

Sorting & Grouping5

jq 'sort' file.json

Sorts an array of scalars or objects.

Link
jq 'sort_by(.key)' file.json

Sorts an array of objects based on a specific field.

Link
jq 'group_by(.key)' file.json

Groups array elements into subarrays based on a field value.

Link
jq 'unique' file.json

Removes duplicates from an array and sorts it.

Link
jq 'unique_by(.key)' file.json

Removes objects with duplicate values for a specific key.

Link

Aggregation3

jq 'min' file.json

Finds the minimum value in an array.

Link
jq 'max' file.json

Finds the maximum value in an array.

Link
jq 'add' file.json

Sums the numbers in an array.

Link

Control Flow2

jq 'if .a then .b else .c end' file.json

Implements standard if-then-else conditional logic.

Link
jq '.a // .b' file.json

Uses the Alternative Operator to provide default values if preceding values are null or false.

Link

Data Modification5

jq '.key = "value"' file.json

Assigns a new static value to a field.

Link
jq '.count += 1' file.json

Increments a numeric value using update assignment.

Link
jq '.tags += ["new"]' file.json

Appends an element to an existing array.

Link
jq 'del(.key)' file.json

Deletes specified keys from an object.

Link
jq '(.values[]) |= . + 1' file.json

Updates every element in an array in place.

Link

Input Handling4

jq -s '.' file.json

Slurps all input JSON objects into a single large array.

Link
jq -R '.' file.txt

Reads input as raw strings instead of JSON.

Link
jq -n '{a: 1}'

Uses null input, useful for generating JSON from scratch without an input file.

Link
jq --arg name val '.'

Passes a value from the shell into a jq variable.

Link

Date & Time4

jq 'now' file.json

Returns the current time as a Unix timestamp.

Link
jq 'todate' file.json

Converts a Unix timestamp to an ISO 8601 string.

Link
jq 'fromdate' file.json

Converts an ISO 8601 string to a Unix timestamp.

Link
jq 'strflocaltime("%Y-%m-%d")' file.json

Formats a timestamp using standard strftime format strings.

Link

Advanced Traversal2

jq '..'

Recursively descends into all values, visiting every node.

Link
jq 'paths'

Outputs the paths to all elements in the JSON document.

Link

Conversion2

jq 'to_entries' file.json

Converts an object into an array of {key, value} pairs.

Link
jq 'from_entries' file.json

Converts an array of {key, value} pairs back into an object.

Link

Formatting Output6

jq '@base64'

Encodes the input string to Base64.

Link
jq '@base64d'

Decodes a Base64 string.

Link
jq '@csv'

Formats an array as a CSV row.

Link
jq '@tsv'

Formats an array as a Tab-Separated Value row.

Link
jq '@uri'

Percent-encodes a string for use in URLs.

Link
jq '@sh'

Escapes a string for safe use in a shell command.

Link

Debugging1

jq 'debug' file.json

Prints the current input to stderr for debugging purposes without affecting output.

Link

Advanced Logic2

jq 'any'

Returns true if any element in the stream matches the condition.

Link
jq 'all'

Returns true only if all elements in the stream match the condition.

Link

Advanced Functions4

jq 'reduce .[] as $item (0; . + $item)'

Reduces an array to a single value (e.g., sum) using an accumulator.

Link
jq 'reduce inputs as $i (.; . + [$i])'

Processes a stream of inputs efficiently without loading everything into memory.

Link
jq 'recurse(.children[])'

Recursively visits a structure defined by a path.

Link
jq 'walk(if type == "object" then del(.null_keys) else . end)'

Applies a function to every node in the JSON tree recursively.

Link

Environment Interaction1

jq 'env'

Accesses system environment variables as a JSON object.

Link

Variables3

jq '. as $root | .items[] | select(.id == $root.target)'

Defines a variable within jq to reference data from a different context.

Link
jq --argjson data '{"a":1}'

Passes a JSON string from the shell and parses it into a jq variable.

Link
jq --slurpfile dict dict.json

Reads a secondary file into a variable array for lookups or joining.

Link

Type Checking3

jq 'type' file.json

Returns the type of the value (object, array, string, number, null, boolean).

Link
jq 'select(type == "string")'

Filters input based on JSON data type.

Link
jq 'arrays, objects, scalars'

Built-in filters to select only arrays, objects, or scalar values.

Link

String Formatting1

jq '"Name: \(.name), ID: \(.id)"'

Uses string interpolation to embed expressions inside strings.

Link

Module Loading1

jq 'import "module" as mod'

Imports a jq library file from the search path.

Link

Automation Workflow1

jq -e . file.json

Sets the shell exit code based on the output (0 if result is not null/false, 1 otherwise).

Link

DevOps Automation1

aws ec2 describe-instances | jq '.Reservations[].Instances[].InstanceId'

Extracts specific resource IDs from complex Cloud API responses.

Link

Log Analysis3

jq -R 'split(" ") | {time:.[0], method:.[3], url:.[4]}'

Parses raw text logs into JSON structure using manual splitting.

Link
jq -s 'group_by(.level) | map({level: .[0].level, count: length})'

Aggregates log entries to count occurrences of specific event levels.

Link
jq 'select(.timestamp > (now - 3600))'

Filters logs to show only entries from the last hour (or specific duration).

Link

Security Automation4

jq 'select(.headers["User-Agent"] | contains("curl"))'

Identifies automated bot traffic by analyzing User-Agent strings.

Link
jq 'select(.response_code >= 500)'

Filters for server-side errors or client errors in web logs.

Link
jq '.Records[] | select(.eventName == "ConsoleLogin" and .errorMessage != null)'

Detects failed console login attempts in CloudTrail logs.

Link
jq -r '. | select(.resources[] | contains("sg-12345"))'

Searches for events related to a specific compromised or target resource ID.

Link

Data Cleaning2

jq 'del(.. | .password?, .secret?, .token?)'

Recursively scrubs sensitive fields like passwords or tokens from a dataset.

Link
jq 'map_values(if . == null then "N/A" else . end)'

Normalizes nulls or empty strings across an object.

Link

Flattening1

jq '[leaf_paths as $path | { "key": $path | join("."), "value": getpath($path) }] | from_entries'

Flattens a deeply nested JSON object into a single-level dot-notation map.

Link

Docker/K8s2

docker inspect container | jq '.[0].NetworkSettings.IPAddress'

Extracts networking or metadata information from container runtime output.

Link
kubectl get secret -o json | jq '.data | map_values(@base64d)'

Decodes Kubernetes secrets directly from the JSON output.

Link

Git Automation1

gh api repos/:owner/:repo/issues | jq 'map(select(.labels[].name == "bug"))'

Filters GitHub API issues by label or state.

Link

Network Analysis1

jq -s 'map(.timestamp) | max - min' packets.json

Calculates the time duration or average latency from a capture file.

Link

Blue Team2

jq 'select(.event_id == 4624 and .logon_type == 10)' winlogs.json

Filters Windows Event Logs for RDP logins (Type 10) or failures.

Link
jq 'group_by(.src_ip) | map({ip: .[0].src_ip, count: length}) | sort_by(.count) | reverse'

Generates a frequency analysis of source IPs to identify potential attackers.

Link

Advanced Transformation2

jq 'reduce inputs as $item (.; .[$item.id] = $item)'

Transforms a stream of objects into a hash map indexed by ID.

Link
jq 'transpose | map(add)' matrix.json

Transposes a matrix (array of arrays) or sums columns.

Link

IAM Analysis1

jq '.Statement[] | select(.Effect == "Allow" and .Action == "*")'

Audits IAM policies for overly permissive wildcard permissions.

Link

Streaming Large Files2

jq --stream 'select(.[0][1] == "id") | .[1]'

Parses massive files token-by-token to reduce memory usage.

Link
jq -cn --stream 'fromstream(inputs | select(.[0][0] == "users"))'

Reconstructs only specific parts of a large JSON file from a stream.

Link

CSV to JSON1

jq -R -s 'split("\n") | .[1:] | map(split(",")) | map({id: .[0], val: .[1]})'

Manually converts raw CSV text into JSON objects (header aware).

Link

Math Statistics2

jq 'map(.value) | add / length' file.json

Calculates the arithmetic mean (average) of an array of numbers.

Link
jq 'map(.value) | sort | .[length/2]' file.json

Calculates the median value of an array.

Link

Comparison1

jq -n --argfile a old.json --argfile b new.json '$a == $b'

Compares two JSON files for strict equality or diffs object keys.

Link

Diffing1

jq -n --argfile a old.json --argfile b new.json '($b - $a)'

Outputs the fields present in the second file that are missing or different in the first.

Link

GeoJSON1

jq '.features[] | select(.properties.population > 1000000)' geo.json

Filters GeoJSON feature collections based on property data.

Link

Encoding2

jq -R -r '@html' input.txt

Escapes HTML entities in a string.

Link
jq '@json' file.json

Serializes a string or object as a JSON string literal.

Link

Error Handling2

jq 'try .foo catch "fallback"'

Catches errors during evaluation and provides a default value.

Link
jq 'try (.a / .b) catch error("division by zero")'

Raises a custom error message to halt processing.

Link

Complex Selection2

jq '.users[] | select([.roles[] | contains("admin")] | any)'

Selects objects where at least one element in a nested array matches a condition.

Link
jq 'select(.key | IN("A", "B", "C"))'

Filters based on a value membership in a specific list.

Link

Combinatorics1

jq 'combinations'

Outputs the Cartesian product of the input arrays.

Link

Path Management2

jq 'setpath(["a","b"]; 1)'

Sets a value at a dynamic path specified by an array.

Link
jq 'getpath(["a","b"])'

Retrieves a value using an array as the path selector.

Link

Deep Equality1

jq 'unique_by(.)'

Checks if complex objects are identical by deduplicating them.

Link

Self-Quine1

jq '.' jq_reference_guide.json

Reads and pretty-prints the file itself to validate its own structure.

Link