How to Access Nested JSON in Python: Simple Guide
To access nested JSON in Python, use
dictionary keys and list indexes step-by-step to reach the desired value. Nested JSON is treated as nested dictionaries and lists, so chain keys and indexes like data['key1']['key2'][0] to get the value.Syntax
Nested JSON data is loaded as Python dictionaries and lists. You access values by chaining dictionary keys and list indexes.
- Dictionary key: Use
data['key']to get the value for a key. - List index: Use
data[index]to get an item from a list. - Combine them to reach nested data, e.g.,
data['key1']['key2'][0].
python
data = {
"user": {
"name": "Alice",
"emails": ["alice@example.com", "alice.work@example.com"]
}
}
# Access nested values
name = data['user']['name']
first_email = data['user']['emails'][0]Example
This example shows how to access nested JSON data loaded as Python dictionaries and lists. It prints the user's name and their first email address.
python
import json json_string = ''' { "user": { "id": 123, "name": "Alice", "emails": ["alice@example.com", "alice.work@example.com"], "address": { "city": "Wonderland", "zip": "12345" } } } ''' # Load JSON string into Python dictionary data = json.loads(json_string) # Access nested values user_name = data['user']['name'] first_email = data['user']['emails'][0] city = data['user']['address']['city'] print(f"Name: {user_name}") print(f"First email: {first_email}") print(f"City: {city}")
Output
Name: Alice
First email: alice@example.com
City: Wonderland
Common Pitfalls
Common mistakes when accessing nested JSON include:
- Using the wrong key name or index, causing
KeyErrororIndexError. - Not checking if a key exists before accessing it.
- Confusing dictionary keys with list indexes.
Always verify the structure or use methods like .get() to avoid errors.
python
data = {
"user": {
"name": "Alice",
"emails": ["alice@example.com"]
}
}
# Wrong: Accessing a missing key causes KeyError
# print(data['user']['phone']) # KeyError
# Right: Use .get() to avoid error
phone = data['user'].get('phone', 'No phone number')
print(phone)Output
No phone number
Quick Reference
Tips for accessing nested JSON:
- Use
dict[key]for dictionaries. - Use
list[index]for lists. - Chain them to go deeper:
data['a']['b'][0]. - Use
.get()to safely access keys. - Print or inspect data structure if unsure.
Key Takeaways
Access nested JSON by chaining dictionary keys and list indexes step-by-step.
Use .get() method to safely access dictionary keys and avoid errors.
Check the JSON structure before accessing to prevent KeyError or IndexError.
Remember JSON objects become Python dictionaries and arrays become lists.
Print or inspect data to understand its nested structure clearly.