Mastering JQ: 15 Useful Examples
Learn how to use jq to query and transform JSON data with practical examples. From basic filtering to advanced transformations.
1. Pretty-Print JSON
The simplest jq command formats JSON with proper indentation. Just use the `.` filter which outputs the entire input.
echo '{"name":"Alice","age":30}' | jq .
2. Extract a Specific Field
Use `.field` to extract a single field from a JSON object. This is the most common jq operation.
echo '{"name":"Alice","age":30}' | jq .name
# "Alice"
3. Access Nested Fields
Chain field access with dots or pipes to reach nested properties: `.user.address.city`
echo '{"user":{"address":{"city":"Beijing"}}}' | jq .user.address.city
# "Beijing"
4. Iterate Over Arrays
Use `.[]` to iterate over array elements. Each element is output separately.
echo '[1,2,3]' | jq .[]
# 1
# 2
# 3
5. Select Elements by Condition
Use `select(.field > value)` to filter array elements based on a condition.
echo '[{"name":"Alice","age":30},{"name":"Bob","age":25}]' | jq '.[] | select(.age > 25)'
# { "name": "Alice", "age": 30 }
6. Transform Array to Object
Use `from_entries` to convert an array of key-value pairs into an object.
echo '[{"key":"name","value":"Alice"},{"key":"age","value":30}]' | jq 'from_entries'
# { "name": "Alice", "age": 30 }
7. Object to Array of Key-Value Pairs
Use `to_entries` to convert an object into an array of `{key, value}` objects.
echo '{"name":"Alice","age":30}' | jq 'to_entries'
# [{"key":"name","value":"Alice"},{"key":"age","value":30}]
8. Map Values
Use `map(expression)` to transform each element of an array.
echo '[1,2,3,4]' | jq 'map(. * 2)'
# [2, 4, 6, 8]
9. Add/Update Fields
Use `+` to merge objects or add new fields to existing JSON.
echo '{"name":"Alice"}' | jq '. + {age: 30, role: "admin"}'
10. Delete Fields
Use `del(.field)` to remove a field from an object.
echo '{"name":"Alice","age":30,"temp":"remove"}' | jq 'del(.temp)'
11. Group By Field
Use `group_by(.field)` to group array elements by a common field value.
echo '[{"city":"BJ","name":"A"},{"city":"SH","name":"B"},{"city":"BJ","name":"C"}]' | jq 'group_by(.city)'
12. Unique Values
Use `unique` or `unique_by(.field)` to remove duplicates from arrays.
echo '[1,2,2,3,3,3]' | jq 'unique'
# [1, 2, 3]
13. String Interpolation
Use `\\(expression)` for string interpolation inside double-quoted strings.
echo '{"name":"Alice","score":95}' | jq '"Hello, \(.name)! Your score is \(.score)."'
14. Raw Output with -r
Use the `-r` flag (or check `Raw Output` in the playground) to output strings without JSON quotes.
echo '{"name":"Alice"}' | jq -r '.name'
# Alice (no quotes)
15. Complex Pipeline
Combine multiple jq features in a single pipeline for powerful data transformations.
echo '{"users":[{"name":"Alice","age":30,"role":"admin"},{"name":"Bob","age":25,"role":"user"},{"name":"Charlie","age":35,"role":"admin"}]}' | jq '.users | map(select(.role == "admin")) | sort_by(.age) | .[] | {name, senior: (.age > 30)}'