Open In App

Sum Integers Stored in JSON using Python

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Summing integers stored in JSON using Python involves reading JSON data, parsing it, and then calculating the sum of integer values. Python’s json module is instrumental in loading JSON data, and the process often includes iterating through the data structure to identify and accumulate integer values. In this context, a common scenario is a JSON file containing various key-value pairs, and the goal is to extract and sum the integer values within.

How To Sum Integers Stored In JSON Using Python?

Below, are the steps of How To Sum Integers Stored In JSON using Python.

Step 1: Import JSON Library

This line imports the json module, which provides methods for working with JSON data.

Python3




import json


Step 2: Read and Parse JSON File

It opens the specified JSON file in read mode ('r'), reads its content, and loads it into a Python data structure using json.load. The loaded data is stored in the variable data.

Python3




#opening file in read mode
  with open(jsonFile, 'r') as file:
    #parsing the json file
      data = json.load(file)


Step 3: Iterate through the data

Below, code initializes a variable `sum` to zero, then iterates through key-value pairs in the `data` dictionary. If the value (`val`) associated with a key is an integer, it adds that integer value to the `sum` variable, effectively accumulating the sum of integers in the dictionary.

Python3




sum = 0
for key, val in data.items():
  if isinstance(val, int): 
    sum += val


Code Example

Example 1: In this example, below code defines a function `sumOfInt` that takes a JSON file path, opens the file, loads its content, and calculates the sum of integers in the JSON data. The result is printed, showcasing the sum of integers in the specified JSON file (‘file.json’ in this case).

Python3




import json
 
def sumOfInt(jsonFile):
    with open(jsonFile, 'r') as file:
        data = json.load(file)
    sum = 0
    for key, val in data.items():
        if isinstance(val, int):
            sum += val
    return sum
 
# Create a file.json with sample data
with open('file.json', 'w') as json_file:
    json.dump({"number1": 10, "number2": 5, "text": "Hello", "number3": 7, "number4": 3}, json_file)
 
# Call the function with the created file
result = sumOfInt('file.json')
 
# Print the result
print(f"The sum of integers in the JSON file is: {result}")


Output

The sum of integers in the JSON file is: 25




Example 2: In this example, below code defines a function `sumIntegers` that takes a JSON file path and an attribute name. It loads the JSON data from the file, iterates through a list of items, and accumulates the sum of integer values found in the specified attribute. The code then creates a ‘file.json’ with sample data, calls the function to calculate the sum of integers in the ‘value’ attribute, and prints the result.

Python3




import json
 
def sumIntegers(jsonFile, attribute):
    with open(jsonFile, 'r') as file:
        data = json.load(file)
 
    sum = 0
    for item in data:
        if attribute in item and isinstance(item[attribute], int):
            sum += item[attribute]
 
    return sum
 
# Create a file.json with a list of items
with open('file.json', 'w') as json_file:
    json.dump([
        {"name": "Item1", "value": 10},
        {"name": "Item2", "value": 5},
        {"name": "Item3", "value": "NotAnInteger"},
        {"name": "Item4", "value": 7}
    ], json_file)
 
# Call the function with the created file and attribute
result = sumIntegers('file.json', 'value')
 
# Print the result
print(f"The sum of integers in the 'value' attribute of JSON file is: {result}")


Output

The sum of integers in the 'value' attribute of JSON file is: 22




Conclusion

In conclusion, summing integers stored in JSON using Python is a task that combines file handling, JSON parsing, and basic arithmetic operations. By leveraging Python’s built-in json module and implementing appropriate logic, developers can efficiently calculate the sum of integer values embedded within JSON structures. This process is versatile and can be adapted to various JSON formats, making it a valuable skill for working with JSON data in Python applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads