I have a situation where I need to read a json file containing statistics of different events coming into my system every 5 mins .I need to aggregate the counts for each of the events show against the events and pass it in another dictionary
This is my sample input dictionary json
"data": [
{
"recievedTime": "2023-04-10T00:05:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 1000
},
{
"EventType": "SMS",
"NumberOfEvents": 55
}
]}
"recievedTime": "2023-04-10T00:10:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 2003
},
{
"EventType": "SMS",
"NumberOfEvents": 45
}
]}
]
I want the output to take the sum of the event counts be in another json object like this:
"data" : [ {"Call": 3003,"SMS" : 100}]
How can I solve this problem ?
2
Answers
You can use a loop to iterate through the events in the input dictionary and add up the counts for each event type. Here’s some example code to achieve this:
This will produce the desired output:
It’s actually quite simple, you just need to us Python’s built-in json module to parse the JSON data, and then loop through the data array.
You can do it like this
Output