Array Operations & Aggregation in jq
Intermediatev1.0.0
Process JSON arrays with jq — map, select, group_by, sort_by, unique_by, flatten, and reduce for transforming, filtering, and aggregating array data in pipelines.
Content
Overview
Arrays are the most common JSON structure in API responses. jq provides powerful array operations — map, select, group_by, sort_by, and reduce — to filter, transform, and aggregate array data.
Why This Matters
- -Data filtering — find items matching complex criteria
- -Aggregation — sum, average, count, and group data
- -Sorting — order results by any field
- -Deduplication — remove duplicates by key
How It Works
Step 1: Map & Select (Filter + Transform)
Step 2: Sorting & Deduplication
Step 3: Grouping & Aggregation
Step 4: Flatten & Combine
Best Practices
- -Use map(select(...)) for filter+transform in one pass
- -Use group_by + map for pivot-table-style aggregation
- -Use sort_by(.field) over sort (which sorts lexicographically)
- -Use unique_by over unique for object arrays
- -Use add for summing (works on numbers and arrays)
Common Mistakes
- -Using sort instead of sort_by (sorts as strings, not by field)
- -Forgetting that group_by requires pre-sorted input? No, jq handles it
- -Using length on objects (returns key count, not useful for "size")
- -Not using // for default values in aggregation (null + number = null)
- -Nested map() when a single pipe would work
FAQ
Discussion
Loading comments...