Home > Blockchain >  How do I add up values in a json file in python?
How do I add up values in a json file in python?

Time:12-12

I'm making a Discord bot to manage a fundraising event in my school. It stores user information in a json file. (Name, How much they donated, etc.) I want to make a command that goes through the json file and adds up donations from each individual user, so I can get the total amount of money raised.

My json file looks like this:

{
   "blacklist":[
      
   ],
   "users":{
      "822679038434213908":{
         "grade":"",
         "paid":15,
         "name":"John Doe",
         "manager":true
      }
   }
}

How would I make it so that it adds up the information of each user (stored under paid) in python and return it?

CodePudding user response:

In order to show how this works, i've added a second user to your json.

The below code example just loops through the users in the json and grabs each user's donation amount and adds it to the sum - finally printing the sum.

json_input = {
   "blacklist":[
      
   ],
   "users":{
      "822679038434213908":{
         "grade":"",
         "paid":15,
         "name":"John Doe",
         "manager":'true'
      },
      "822679038434213909":{
         "grade":"",
         "paid":20,
         "name":"John Doe",
         "manager":'true'
      }
   }
}

sum = 0
for user in json_input['users']:
    sum  = json_input['users'][user]['paid']

print(sum)
  • Related