Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method for parsing nested JSON with Python involves using the json library to load the JSON string into a Python dictionary or list. Once the JSON is loaded into a variable, it can be accessed using the keys and indexes of the dictionary or list.

Here is an example of parsing nested JSON using Python:

import json

# Example JSON string
json_str = '{"name": "John Smith", "age": 35, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA"}}'

# Load JSON string into a dictionary
data = json.loads(json_str)

# Access top-level keys
print(data['name'])     # Output: John Smith
print(data['age'])      # Output: 35

# Access nested keys
print(data['address']['street'])    # Output: 123 Main St
print(data['address']['city'])      # Output: Anytown
print(data['address']['state'])     # Output: CA

In this example, we first import the json library and then define a JSON string. We then use the json.loads() method to load the JSON string into a dictionary called data. We can then access the top-level keys by specifying the key name as a string in square brackets. For nested keys, we use multiple square brackets to access the keys at each level.