Reputation: 1661
I have the following JSON data :
{
"data": [
{"date": "2018-08-22","value": 3},
{"date": "2018-08-30","value": 5},
{"date": "2018-09-01","value": 5},
{"date": "2018-09-22","value": 9},
{"date": "2018-09-28","value": 4},
{"date": "2018-10-18","value": 2},
{"date": "2018-10-23","value": 1}
]
}
I would like to get the average per month. My expected output is the following :
{
"data": [
{"month": "2018-08","avg": 4},
{"month": "2018-09","avg": 6},
{"month": "2018-10","avg": 3}
]
}
How can I do that ?
Upvotes: 0
Views: 365
Reputation: 116910
This question is almost identical to
JSON parsing - group by date range with JQ
and the solution given there can easily be adapted to the problem here:
def bucket: sub("-\\d+$"; "");
.data
| reduce .[] as $pair ({};
.[$pair.date | bucket] += [$pair.value])
| {data: [to_entries[] | {month: .key, avg: (.value| add/length)}]}
Upvotes: 1