What Is jq?
jq is a lightweight command-line JSON processor. It allows you to parse, filter, transform, and format JSON data directly in your terminal. It is invaluable for working with APIs, configuration files, and log data on your Breeze.
Installing jq
sudo apt update
sudo apt install -y jq
jq --versionBasic Usage
# Pretty-print JSON
echo '{"name":"server","status":"active"}' | jq .
# Extract a specific field
echo '{"name":"web-01","ip":"10.0.1.5"}' | jq .name
# Output: "web-01"
# Get raw string without quotes
echo '{"name":"web-01"}' | jq -r .name
# Output: web-01Working with Arrays
# Sample data
DATA='[{"name":"web-01","cpu":45},{"name":"web-02","cpu":78},{"name":"db-01","cpu":30}]'
# Get all names
echo "$DATA" | jq '.[].name'
# Get the first element
echo "$DATA" | jq '.[0]'
# Filter: servers with CPU above 50
echo "$DATA" | jq '.[] | select(.cpu > 50)'Transforming Data
# Create new objects from existing data
echo "$DATA" | jq '.[] | {server: .name, load: .cpu}'
# Build a CSV-style output
echo "$DATA" | jq -r '.[] | [.name, .cpu] | @csv'Working with API Responses
# Parse a curl response
curl -s https://api.example.com/servers | jq '.data[] | {id, name, status}'
# Count items in an array
curl -s https://api.example.com/servers | jq '.data | length'
# Sort by a field
curl -s https://api.example.com/servers | jq '.data | sort_by(.created_at)'Useful Patterns
# Merge two JSON objects
echo '{"a":1}' | jq '. + {"b":2}'
# Convert JSON to key=value pairs
echo '{"host":"web-01","port":8080}' | jq -r 'to_entries[] | "\(.key)=\(.value)"'
# Update a value in-place
jq '.database.port = 5432' config.json > tmp.json && mv tmp.json config.jsonTips
- Use
jq -eto set exit code based on output (useful in scripts) - Pipe
jq -routput toxargsfor further processing - Combine with
curlfor quick API exploration