Below is one standard solution using jq’s built‐in grouping and transformation functions:
jq 'group_by(.a)[] | { a: .[0].a, count: map(.b | length) | add }'
Result (the output is an object with each unique a
as a key and the total count of b
entries as the value):
{
"foo": 3,
"bar": 0
}
Grouping by a
:
The command starts with:
jq group_by(.a)[]
This groups all objects in the array that share the same a
value into subarrays. Each subarray contains all objects with that same a
.
Extracting the Unique Key:
For each group (which is an array), the expression:
jq .[0].a
extracts the common a
value from the first item. Since all objects in the group have the same a
, this is safe.
Counting Entries in b
:
The expression:
jq map(.b | length) | add
takes the current group (an array of objects), maps each object to the length of its .b
array, and then sums them with add
. This sum represents the total count of all entries in b
for that particular a
.
Building the Output Object:
The { a: .[0].a, count: ... }
syntax creates an object with two fields: the a
value and the computed count
.
In the future if you'd like to use jq in any JetBrains IDE, please check out my plugin: https://plugins.jetbrains.com/plugin/23360-jqexpress