Loading...
Loading...
Learn how to use jq to query and transform JSON data with practical examples. From basic filtering to advanced transformations.
The simplest jq command formats JSON with proper indentation. Just use the `.` filter which outputs the entire input.
echo '{"name":"Alice","age":30}' | jq .
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"
Chain field access with dots or pipes to reach nested properties: `.user.address.city`
echo '{"user":{"address":{"city":"Beijing"}}}' | jq .user.address.city
# "Beijing"
Use `.[]` to iterate over array elements. Each element is output separately.
echo '[1,2,3]' | jq .[]
# 1
# 2
# 3
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 }
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 }
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}]
Use `map(expression)` to transform each element of an array.
echo '[1,2,3,4]' | jq 'map(. * 2)'
# [2, 4, 6, 8]
Use `+` to merge objects or add new fields to existing JSON.
echo '{"name":"Alice"}' | jq '. + {age: 30, role: "admin"}'
Use `del(.field)` to remove a field from an object.
echo '{"name":"Alice","age":30,"temp":"remove"}' | jq 'del(.temp)'
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)'
Use `unique` or `unique_by(.field)` to remove duplicates from arrays.
echo '[1,2,2,3,3,3]' | jq 'unique'
# [1, 2, 3]
Use `\\(expression)` for string interpolation inside double-quoted strings.
echo '{"name":"Alice","score":95}' | jq '"Hello, \(.name)! Your score is \(.score)."'
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)
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)}'