Navigating Nested JSON Structures in Python
Accessing Nested Keys
When working with JSON data in Python, you may encounter nested structures, where the values of the key-value pairs can be other JSON objects or arrays. To access the nested keys, you can use a combination of dictionary and list indexing.
Here's an example of a nested JSON object:
{
"name": "John Doe",
"age": 35,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"hobbies": ["reading", "hiking", "photography"]
}
To access the nested keys, you can use the following syntax:
import json
## Sample JSON data
json_data = {
"name": "John Doe",
"age": 35,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"hobbies": ["reading", "hiking", "photography"]
}
## Access nested keys
print(json_data["address"]["street"]) ## Output: 123 Main St
print(json_data["hobbies"][1]) ## Output: hiking
In the example above, we first import the json
module, which provides functions for parsing and manipulating JSON data. We then define a sample JSON object and use dictionary and list indexing to access the nested keys.
Handling Nested Arrays
When the value of a key is an array, you can use a combination of dictionary and list indexing to access the nested elements.
## Sample JSON data with nested array
json_data = {
"name": "John Doe",
"age": 35,
"addresses": [
{
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
{
"street": "456 Oak Rd",
"city": "Othertown",
"state": "NY",
"zip": "67890"
}
]
}
## Access nested array elements
for address in json_data["addresses"]:
print(address["street"])
## Output:
## 123 Main St
## 456 Oak Rd
In this example, the "addresses"
key contains an array of address objects. We use a for
loop to iterate over the array and print the "street"
value of each address.
By understanding how to navigate nested JSON structures in Python, you can effectively extract and manipulate the data you need for your applications.