DevTools

jq CLI

jq commands for JSON processing and transformation.

38 commands
Windows MacOS Linux
#json-processing #data

Basic Filters

Pretty-print entire JSON input
jq '.'
Extract a top-level field called name
jq '.name'
Get the first element of the users array
jq '.users[0]'
Iterate array and extract id from each element
jq '.[] | .id'
Output raw string without quotes
jq -r '.name'
Compact single-line output
jq -c '.'

Object Operations

Construct a new object with selected fields
jq '{name: .name, age: .age}'
Add or overwrite a field in an object
jq '. + {"status": "active"}'
Delete a field from an object
jq 'del(.password)'
List all keys of an object
jq 'keys'
Convert object to array of key-value pairs
jq 'to_entries'
Convert key-value pair array back to object
jq 'from_entries'

Array Operations

Count elements in an array
jq '.items | length'
Transform each element with an expression
jq '.items | map(.price * .qty)'
Filter array elements by condition
jq '[.items[] | select(.active)]'
Sort array by a field
jq '.items | sort_by(.name)'
Remove duplicates by a field
jq '.items | unique_by(.id)'
Get the first element of an array
jq '.items | first'
Flatten nested arrays into one
jq '[.a, .b] | flatten'

Conditionals

Conditional expression
jq 'if .age > 18 then "adult" else "minor" end'
Select elements matching condition
jq '.items[] | select(.price > 10)'
Alternative operator for null values
jq '.val // "default"'
Filter with conditional in map
jq 'map(if .status == "ok" then . else empty end)'

String Functions

Convert string to lowercase
jq '.name | ascii_downcase'
Convert string to uppercase
jq '.name | ascii_upcase'
Split string into array by delimiter
jq '.msg | split(" ")'
Join array elements into a string
jq '.items | join(", ")'
Test if string matches a regex
jq '.name | test("^foo")'
Remove prefix from a string
jq '.path | ltrimstr("/api")'

Advanced

Slurp multiple JSON inputs into an array
jq -s '.'
Pass external variable into jq expression
jq --arg v "hello" '.msg = $v'
Build JSON from multiple inputs with null input
jq -n '{items: [inputs]}'
Group array elements by a field value
jq 'group_by(.category)'
jq '[.[] | {(.key): .value}] | add' # Reshape array of pairs into a merged object
Reduce array to a single accumulated value
jq 'reduce .[] as $x (0; . + $x)'

Quick Commands

Pretty-print a JSON file
jq '.' file.json
Filter array elements where active is true
jq '.[] | select(.active)' file.json
Extract name field from each item as raw text
jq -r '.items[].name' file.json