jq group_by: group and count items
group_by(f) sorts an array by f and splits it into an array of groups. Then you summarise each group with map.
What group_by returns
An array of arrays — one inner array per distinct value.
group_by(.team) | map(map(.name))CompactTry itInput
[
{
"name": "Ada",
"age": 36,
"team": "core"
},
{
"name": "Linus",
"age": 28,
"team": "kernel"
},
{
"name": "Grace",
"age": 45,
"team": "core"
},
{
"name": "Ken",
"age": 28,
"team": "kernel"
}
]Output
[["Ada","Grace"],["Linus","Ken"]]jq -c 'group_by(.team) | map(map(.name))' data.jsonCount per group
Inside each group, .[0] gives the shared value and length the count.
group_by(.team) | map({team: .[0].team, count: length})CompactTry itInput
[
{
"name": "Ada",
"age": 36,
"team": "core"
},
{
"name": "Linus",
"age": 28,
"team": "kernel"
},
{
"name": "Grace",
"age": 45,
"team": "core"
},
{
"name": "Ken",
"age": 28,
"team": "kernel"
}
]Output
[{"team":"core","count":2},{"team":"kernel","count":2}]jq -c 'group_by(.team) | map({team: .[0].team, count: length})' data.jsonAs an object
group_by(.team) | map({(.[0].team): length}) | addCompactTry itInput
[
{
"name": "Ada",
"age": 36,
"team": "core"
},
{
"name": "Linus",
"age": 28,
"team": "kernel"
},
{
"name": "Grace",
"age": 45,
"team": "core"
},
{
"name": "Ken",
"age": 28,
"team": "kernel"
}
]Output
{"core":2,"kernel":2}jq -c 'group_by(.team) | map({(.[0].team): length}) | add' data.jsonSum or average per group
group_by(.team) | map({team: .[0].team, avgAge: (map(.age) | add / length)})CompactTry itInput
[
{
"name": "Ada",
"age": 36,
"team": "core"
},
{
"name": "Linus",
"age": 28,
"team": "kernel"
},
{
"name": "Grace",
"age": 45,
"team": "core"
},
{
"name": "Ken",
"age": 28,
"team": "kernel"
}
]Output
[{"team":"core","avgAge":40.5},{"team":"kernel","avgAge":28}]jq -c 'group_by(.team) | map({team: .[0].team, avgAge: (map(.age) | add / length)})' data.jsonMost common first
Sort the summary by count, descending.
[.[] | .msg] | group_by(.) | map({msg: .[0], n: length}) | sort_by(-.n)SlurpCompactTry itInput
{"level":"info","msg":"started","ms":12}
{"level":"error","msg":"db timeout","ms":5003}
{"level":"info","msg":"request","ms":48}
{"level":"error","msg":"db timeout","ms":5011}Output
[{"msg":"db timeout","n":2},{"msg":"request","n":1},{"msg":"started","n":1}]jq -s -c '[.[] | .msg] | group_by(.) | map({msg: .[0], n: length}) | sort_by(-.n)' data.jsonCommon mistakes
group_byneeds an array. For NDJSON, add-s(slurp) first.- Grouping by a field that is missing on some items puts those items in a
nullgroup.
Practice
Open the jq Playground with your own JSON — it runs the real jq 1.8 in your browser, so nothing is uploaded. The jq cheat sheet lists every filter from these lessons on one page.