Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
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.
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.
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.
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.
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.
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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The 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.
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.
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.