snippetbashTippending
jq recipes for JSON processing on the command line
Viewed 0 times
jqjsonfiltertransformextractcommand-line
Problem
Need to extract, filter, and transform JSON data from APIs or files on the command line.
Solution
Common jq patterns:
# Pretty print
cat data.json | jq .
# Extract field
echo '{"name":"Alice","age":30}' | jq '.name' # "Alice"
echo '{"name":"Alice","age":30}' | jq -r '.name' # Alice (raw)
# Array operations
jq '.[0]' arr.json # First element
jq '.[-1]' arr.json # Last element
jq '. | length' arr.json # Array length
jq '.[] | .name' arr.json # Extract field from each
# Filtering
jq '.[] | select(.age > 25)' users.json
jq '.[] | select(.status == "active")' items.json
jq '[.[] | select(.price < 100)]' products.json # Keep as array
# Transform
jq '.[] | {name, email}' users.json # Pick fields
jq '.[] | .name + " (" + .role + ")"' users.json # String concat
jq '[.[] | .price] | add' items.json # Sum prices
# Group and count
jq 'group_by(.status) | map({status: .[0].status, count: length})' items.json
# Create new objects
jq '{total: length, items: [.[].name]}' arr.json
# Handle nulls
jq '.missing // "default"' data.json # Default value
# Pretty print
cat data.json | jq .
# Extract field
echo '{"name":"Alice","age":30}' | jq '.name' # "Alice"
echo '{"name":"Alice","age":30}' | jq -r '.name' # Alice (raw)
# Array operations
jq '.[0]' arr.json # First element
jq '.[-1]' arr.json # Last element
jq '. | length' arr.json # Array length
jq '.[] | .name' arr.json # Extract field from each
# Filtering
jq '.[] | select(.age > 25)' users.json
jq '.[] | select(.status == "active")' items.json
jq '[.[] | select(.price < 100)]' products.json # Keep as array
# Transform
jq '.[] | {name, email}' users.json # Pick fields
jq '.[] | .name + " (" + .role + ")"' users.json # String concat
jq '[.[] | .price] | add' items.json # Sum prices
# Group and count
jq 'group_by(.status) | map({status: .[0].status, count: length})' items.json
# Create new objects
jq '{total: length, items: [.[].name]}' arr.json
# Handle nulls
jq '.missing // "default"' data.json # Default value
Why
jq is the standard tool for JSON processing in shell scripts. It replaces Python/Node one-liners for quick data extraction.
Revisions (0)
No revisions yet.