Solve - (JSON) KeyError exception in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

Solve - (JSON) KeyError exception in Python #

To solve the (JSON) KeyError exception in Python, use the json.loads() method to parse the JSON string into a native Python object and conditionally check if the key is present in the dictionary before accessing it.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' # 👇️ parse JSON string to Python dict my_dict = json.loads(my_json) print(my_dict) # 👉️ {'name': 'Alice', 'age': 30} # 👇️ check if key is present in dictionary if 'country' in my_dict: print(my_dict['country'])

The json.loads method parses a JSON string into a native Python object.

We used the in operator to check if the country key is present in the dictionary before accessing it.

When used with a dictionary, the operators check for the existence of the specified key in the dict object.

Alternatively, you can check if the key is not in the dictionary and set it to a default value, e.g. an empty string or an empty list.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' my_dict = json.loads(my_json) print(my_dict) # 👉️ {'name': 'Alice', 'age': 30} if 'country' not in my_dict: my_dict['country'] = '' print(my_dict['country']) # 👉️ ''

We only set the country key to an empty string if it isn't already present in the dictionary.

When debugging, use the dict.keys() method to print the dictionary's keys.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' my_dict = json.loads(my_json) print(my_dict) # 👉️ {'name': 'Alice', 'age': 30} # 👇️ ['name', 'age'] print(list(my_dict.keys()))

If you try to access any other key, you'd get the KeyError exception.

If you only need to access a specific key and need to ignore the KeyError exception, use the dict.get() method.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' my_dict = json.loads(my_json) print(my_dict) # 👉️ {'name': 'Alice', 'age': 30} print(my_dict.get('country')) # 👉️ None print(my_dict.get('country', 'default value')) # 👉️ 'default value'

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 arguments:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

Make sure you aren't trying to access the key incorrectly.

main.py
import json my_json = r'{"address": {"country": "Austria"}}' my_dict = json.loads(my_json) print(my_dict) # 👉️ {'address': {'country': 'Austria'}} print(my_dict['address']['country']) # 👉️ 'Austria'

Notice that we first have to access the address key before accessing the nested country key.

If you have an array, make sure to access it at a specific index before trying to access a key.

main.py
import json my_json = r'[{"address": {"country": "Austria"}}]' my_list = json.loads(my_json) print(my_list) # 👉️ [{'address': {'country': 'Austria'}}] print(my_list[0]['address']['country']) # 👉️ 'Austria'

We parsed the JSON string into a list. Notice that we first have to access the list at index 0 to get a dict object.

Once we have a dict object, we can access its specific keys.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.