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
JSON Parsing Errors in Python
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: