1. Core Navigation & Field Selection Filters
The simplest `jq` expression is the identity filter `.`, which pretty-prints incoming JSON. To extract specific keys, append property names after dots (e.g. `.user.email`).
# Sample JSON: {"user": {"name": "Alex", "email": "alex@example.com"}, "active": true}
# 1. Extract nested key
echo '{"user": {"name": "Alex", "email": "alex@example.com"}}' | jq '.user.email'
# Output: "alex@example.com"
# 2. Extract raw unquoted string (with -r flag)
echo '{"user": {"name": "Alex"}}' | jq -r '.user.name'
# Output: Alex2. Array Iteration & Slicing (`.[]`)
To iterate over array items, use the array value iterator `.[]`. Combine it with index brackets to extract specific array slices or element positions.
# Sample Array: [{"id": 1, "name": "A"}, {"id": 2, "name": "B"}]
# 1. Extract first element in array
echo '[{"name": "Alice"}, {"name": "Bob"}]' | jq '.[0]'
# 2. Extract all names across array items into a flat list
echo '[{"name": "Alice"}, {"name": "Bob"}]' | jq '.[].name'
# Output:
# "Alice"
# "Bob"3. Advanced Filtering with `select()` & Conditions
The `select(boolean_expression)` function filters JSON objects based on conditional evaluation (like SQL WHERE clauses).
# Filter users where age > 25 and status is "active"
cat users.json | jq '.[] | select(.age > 25 and .status == "active")'
# Reconstruct new customized JSON object structure
cat users.json | jq '.[] | select(.active == true) | {username: .name, user_email: .email}'