In modern DevOps, cloud engineering, and API development, JSON is ubiquitous. Whether interacting with Kubernetes APIs, AWS CLI outputs, Docker inspections, or third-party webhooks, processing raw JSON with grep and awk is fragile and error-prone. jq is a domain-specific query language that allows you to parse, transform, and reshape JSON streams with mathematical precision.
Top 6 Everyday jq Patterns
1. Extracting Specific Object Keys
curl -s https://api.github.com/repos/jqlang/jq | jq '.name, .stargazers_count'
2. Unpacking Arrays and Selecting Objects
Extract only containers with status "running" from Docker:
docker inspect my_container | jq '.[0].State | {Running: .Running, StartedAt: .StartedAt}'
3. Filtering with Conditions
cat users.json | jq '.[] | select(.age >= 18 and .active == true) | .email'
4. Transforming Objects into Arrays
cat data.json | jq '[.users[] | {id: .id, name: .name}]'
5. Outputting Raw Strings for Bash Variables
The -r flag strips surrounding JSON quotation marks so values can be stored in bash variables cleanly:
TOKEN=$(curl -s https://auth.api/login | jq -r '.access_token')
jq Stream Processing Model
Common jq Filters Quick Reference
| Filter Expression | Function | Example Output |
|---|---|---|
| .key | Extract value of field | "production" |
| .[] | Unpack array elements | Separate streams for each item |
| keys | List all available object keys | ["id", "name", "status"] |
| @csv | Format array as CSV line | "1","admin","active" |
Always enclose jq filters in single quotes ('...') rather than double quotes in your terminal. Double quotes cause the bash shell to interpret dollar signs ($var) and backticks as bash expressions before jq ever receives them, causing syntax errors. If you need to pass a bash variable into jq, use the official flag: jq --arg myvar "$VAR" '.[] | select(.id == $myvar)'.
For the complete official language specification and interactive sandbox, visit jqlang.github.io/jq.
Discussion & Issues
Comments
Post a Comment