Issue
I've got a file with these jsons:
{"count":42,"day":"2023-06-22","id":"123"}
{"count":12,"day":"2023-06-22","id":"456"}
{"count":23,"day":"2023-06-23","id":"123"}
{"count":44,"day":"2023-06-23","id":"789"}
{"count":65,"day":"2023-06-21","id":"456"}
Actually I don't care about the day
and want to group my records by id
and sum the count
. Expected result:
{"id":"123","count":65}
{"id":"456","count":77}
{"id":"789","count":44}
How would I achieve this with JQ?
Solution
Use group_by
to group the objects.
jq -cs 'group_by(.id)[] | {id: .[0].id, count: map(.count) | add}' < file.json
-s
wraps the whole input into a large array so you can process all the objects instead of iterating them one by one;-c
compresses the output so it looks like the desired one.
Answered By - choroba Answer Checked By - Willingham (WPSolving Volunteer)