Open In App

JSON Parsing Errors in Python

Last Updated : 24 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Python3




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

Python3




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.

Python3




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

Python3




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.

Python3




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.

Python3




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.

Python3




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

Python3




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.

Python3




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

Python3




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads