Sum Integers Stored in JSON using Python
Last Updated :
24 Apr, 2025
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
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}")
OutputThe 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}")
OutputThe 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.
Similar Reads
Convert CSV to JSON using Python
Converting CSV to JSON using Python involves reading the CSV file, converting each row into a dictionary and then saving the data as a JSON file. For example, a CSV file containing data like names, ages and cities can be easily transformed into a structured JSON array, where each record is represent
2 min read
Convert Bytes To Json using Python
When dealing with complex byte data in Python, converting it to JSON format is a common task. In this article, we will explore different approaches, each demonstrating how to handle complex byte input and showcasing the resulting JSON output. Convert Bytes To JSON in PythonBelow are some of the ways
2 min read
Saving API Result Into JSON File in Python
As Python continues to be a prominent language for web development and data processing, working with APIs and storing the obtained data in a structured format like JSON is a common requirement. In this article, we will see how we can save the API result into a JSON file in Python. Saving API Result
3 min read
Sum all Items in Python List without using sum()
In Python, typically the sum() function is used to get the sum of all elements in a list. However, there may be situations where we are required to sum the elements without using the sum() function. Let's explore different methods to sum the items in a list manually.Using for loopUsing a for loop is
2 min read
Convert JSON to string - Python
Data is transmitted across platforms using API calls. Data is mostly retrieved in JSON format. We can convert the obtained JSON data into String data for the ease of storing and working with it. Python provides built-in support for working with JSON through the json module. We can convert JSON data
2 min read
Python | Sum of squares in list
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let's discuss
5 min read
Python - Get sum of last K list items using slice
Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last K elements and do its summation. Letâs discuss certain solution to perform this task. Metho
5 min read
Python - Get summation of numbers in string list
Sometimes, while working with data, we can have a problem in which we receive series of lists with data in string format, which we wish to accumulate as list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + int() This is the brute force method to perform this
3 min read
Single Vs Double Quotes in Python Json
JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for data storage and exchange between web servers and clients. In Python, dealing with JSON is a common task, and one of the decisions developers face is whether to use single or double quotes for string represent
3 min read
Decoding Json String with Single Quotes in Python
We are given a JSON string with single quotes and our task is to parse JSON with single quotes in Python. In this article, we will see how we can parse JSON with single quotes in Python. Example: Input: json_string = "{'name': 'Ragu','age': 30,'salary':30000,'address': { 'street': 'Gradenl','city':
2 min read