Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading