How to get the sum from the JSON file use Python

Viewed 33

I have code which read data from JSON file

    i = 0

while i < 10:
    with open('output/{}.json'.format(i), 'r') as jsonFile:
        jsonObject = json.load(jsonFile)
        jsonData = jsonObject["attributes"]
        jsonFile.close()

        for x in jsonData:
            keys = x.values()
            #print(keys)
            price = x["price"]
            print(price)

I have output like this: enter image description here

Question: How can I return the sum of price?

PS My JSON file

{
    "attributes": [
        {
            "trait_type": "Background",
            "value": "brown",
            "price": 35
        },
        {
            "trait_type": "Rock",
            "value": "red",
            "price": 100
        },
        {
            "trait_type": "Apron",
            "value": "white",
            "price": 100
        }
    ]
}
1 Answers

Iterate over the dictionaries and sum the values with sum()

with open('output.json', 'r') as jsonFile:
    jsonObject = json.load(jsonFile)
    jsonData = jsonObject["attributes"]

print(sum(d['price'] for d in jsonData)) # 235

As a side note, when you use with you don't need to close the file explicitly, remove jsonFile.close().

Related