JSON Parsing Errors in Python
Last Updated :
23 Apr, 2025
JSON is a widely used format for exchanging data between systems and applications. Python provides built-in support for working with JSON data through its JSON module. However, JSON parsing errors can occur due to various reasons such as incorrect formatting, missing data, or data type mismatches.
There are different JSON parsing errors that can occur depending on the specific scenario when the JSON data is being parsed. Some common JSON parsing errors that occur in Python are:
Python JSONDecodeError
JSONDecodeError is an error that occurs when the JSON data is invalid, such as having missing or extra commas, missing brackets, or other syntax errors. This error is typically raised by the json.loads() function when it’s unable to parse the JSON data.
Problem Statement
In this example, we have created a json_data with keys name, age, and city then we have used the try-catch block to get the error if it comes otherwise we are printing the data.
Python
import json
# Missing closing brace '}' at the end
json_data = '{ "name": "Om Mishra", "age": 22, "city": "Ahmedabad" '
try:
data = json.loads(json_data)
print(data)
except json.JSONDecodeError as e:
print("Invalid JSON syntax:", e)
Output
Invalid JSON syntax: Expecting ',' delimiter: line 1 column 55 (char 54)
Solution
Python
import json
# Missing closing brace '}' at the end
json_data = '{ "name": "Om Mishra", "age": 22, "city": "Ahmedabad" }'
try:
data = json.loads(json_data)
print(data)
except json.JSONDecodeError as e:
print("Invalid JSON syntax:", e)
Output
{'name': 'Om Mishra', 'age': 22, 'city': 'Ahmedabad'}
Python KeyError
KeyError is an error that occurs when the JSON data does not contain the expected key. This error is raised when a key is accessed that does not exist in the JSON data.
Problem Statement
In this example, we have created a json_data with the keys name, age then we have used the try-catch block to get the error if it comes otherwise we are printing the data of the key city.
Python
import json
# JSON does not contain key "city"
json_data = '{ "name": "Om Mishra", "age": 22 }'
try:
data = json.loads(json_data)
city = data["city"]
print(city)
except KeyError:
print("Missing 'city' key in JSON data")
Output
Missing 'city' key in JSON data
Explanation
In this example, we have a JSON string json_data that only contains name and age keys. When we try to access the city key in the JSON, we get a KeyError because the city key does not exist in the JSON data. To fix this error, add a city key to the JSON.
Solution
Python
import json
# JSON does not contain key "city"
json_data = '{ "name": "Om Mishra", "age": 22 }'
try:
data = json.loads(json_data)
city = data["name"]
print(city)
except KeyError:
print("Missing 'city' key in JSON data")
Output
Om Mishra
Python ValueError
ValueError occurs when the JSON data contains a value that is not of the expected data type, such as a string instead of an integer or vice versa. It is raised when JSON is parsed to access a value with an invalid data type.
Problem Statement
In this example, we have created a json_data with the keys name, age then we have used the try-catch block to get the error if it comes otherwise we are printing the age integer value.
Python
import json
# age has string value
json_data = '{ "name": "Om Mishra", "age": "twenty two" }'
try:
data = json.loads(json_data)
age = int(data["age"])
print(age)
except ValueError:
print("'age' value is not a valid integer in JSON data")
Output
'age' value is not a valid integer in JSON data
Explanation
In this example, we try to parse the json_data, which successfully loads the JSON data into a dictionary. However, when we try to access the age key, which has a string value of “twenty-two“, and then try to convert it into an integer using int(), we get a ValueError because the string “twenty-two” cannot be converted into an integer. To fix this error, change the string value “twenty-two” to integer 22.
Python
import json
# age has string value
json_data = '{ "name": "Om Mishra", "age": "22" }'
try:
data = json.loads(json_data)
age = int(data["age"])
print(age)
except ValueError:
print("'age' value is not a valid integer in JSON data")
Output
22
Python TypeError
TypeError is another common error that can occur when working with JSON data in Python. This error is raised when there is a mismatch between the expected data type and the actual data type of a certain value in the JSON data.
Problem Statement
In this example, we have created a json_data with the keys name, age then we have used the try-catch block to get the error if it comes otherwise we are printing the sum of the number key which consists of numbers from 1 to 5.
Python
import json
# 5 is in string type
json_data = '{ "numbers": [1, 2, 3, 4, "5"] }'
data = json.loads(json_data)
numbers = data["numbers"]
try:
total = sum(numbers)
print(total)
except TypeError:
print("Mismatch Type Detected")
Output
Mismatch Type Detected
Explanation
In this example, we catch the TypeError exception when any data type other than an integer is identified. To fix this error remove quotations around 5 in the numbers list.
Solution
Python
import json
# 5 is in string type
json_data = '{ "numbers": [1, 2, 3, 4, 5] }'
data = json.loads(json_data)
numbers = data["numbers"]
try:
total = sum(numbers)
print(total)
except TypeError:
print("Mismatch Type Detected")
Output
15
Python AttributeError
This error occurs when you try to access an attribute that does not exist in the JSON data. It is raised when an attribute is accessed that does not exist in the JSON data. (Each comma-separated key-value pair in JSON is called an attribute).
Problem Statement
In this example, we have created a json_data with the keys name, age then we have used the try-catch block to get the error if it comes otherwise we are printing the person object name key.
Python
import json
json_data = '{ "person": { "name": "Om Mishra", "age": 30 } }'
try:
data = json.loads(json_data)
name = data["person"].name
print(name)
except AttributeError:
print("Invalid key in JSON data. Expected 'name' key to be present.")
Output
Invalid key in JSON data. Expected 'name' key to be present.
Explanation
In this example, we try to access the name attribute of the person object in the data dictionary using dot notation. However, the name attribute does not exist in the person object, so Python raises an AttributeError with the message “‘dict’ object has no attribute ‘name'”. To fix this error, we can access the name attribute using dictionary notation instead.
name = data["person"]["name"]
Solution
Python
import json
json_data = '{ "person":
{ "name": "Om Mishra", "age": 30 } }'
try:
data = json.loads(json_data)
name = data["person"]["name"]
print(name)
except AttributeError:
print("Invalid key in JSON data."+
"Expected 'name' key to be present.")
Output
Om Mishra
Similar Reads
Indentation Error in Python
In this article, we will explore the Indentation Error in Python. In programming, we often encounter errors. Indentation Error is one of the most common errors in Python. It can make our code difficult to understand, and difficult to debug. Python is often called a beautiful language in the programm
3 min read
NZEC error in Python
While coding on various competitive sites, many people must have encountered NZEC errors. NZEC (non-zero exit code), as the name suggests, occurs when your code fails to return 0. When a code returns 0, it means it is successfully executed otherwise, it will return some other number depending on the
3 min read
json.loads() in Python
JSON is a lightweight data format used for storing and exchanging data across systems. Python provides a built-in module called json to work with JSON data easily. The json.loads() method of JSON module is used to parse a valid JSON string and convert it into a Python dictionary. In this article, we
4 min read
Errors and Exceptions in Python
Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow. Syntax Errors in PythonSyntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in
3 min read
json.load() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json . To use this feature, we import the json package in Pyth
4 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data f
2 min read
json.dumps() in Python
JSON is an acronym that stands for JavaScript Object Notation. Despite its name, JSON is a language agnostic format that is most commonly used to transmit data between systems, and on occasion, store data. Programs written in Python, as well as many other programming languages, can ingest JSON forma
6 min read
Handling EOFError Exception in Python
In Python, an EOFError is raised when one of the built-in functions, such as input() or raw_input() reaches the end-of-file (EOF) condition without reading any data. This commonly occurs in online IDEs or when reading from a file where there is no more data left to read. Example: [GFGTABS] Python n
4 min read
Broken Pipe Error in Python
In this article, we will discuss Pipe Error in python starting from how an error is occurred in python along with the type of solution needed to be followed to rectify the error in python. So, let's go into this article to understand the concept well. With the advancement of emerging technologies in
4 min read
Python Print Exception
In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions. Using as keywordas keyword lets u
3 min read