How to parse nested JSON objects in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To parse nested JSON objects in Python, you can use the json module’s loads() method to load the JSON data into a Python object. Once the data is in a Python object, you can access nested objects using dictionary-style indexing or attribute access syntax, depending on the structure of the JSON data.

Here is an example:

import json

# Example JSON data
json_str = '''
{
  "person": {
    "name": "John",
    "age": 30,
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "state": "CA"
    },
    "phones": [
      {
        "type": "home",
        "number": "555-1234"
      },
      {
        "type": "work",
        "number": "555-5678"
      }
    ]
  }
}
'''

# Load JSON data into Python object
data = json.loads(json_str)

# Access nested objects using dictionary-style indexing or attribute access syntax
name = data["person"]["name"]
age = data["person"]["age"]
street = data["person"]["address"]["street"]
city = data["person"]["address"]["city"]
state = data["person"]["address"]["state"]
home_phone = data["person"]["phones"][0]["number"]
work_phone = data["person"]["phones"][1]["number"]

# Print the parsed data
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Address: {street}, {city}, {state}")
print(f"Home phone: {home_phone}")
print(f"Work phone: {work_phone}")

This will output:

Name: John
Age: 30
Address: 123 Main St, Anytown, CA
Home phone: 555-1234
Work phone: 555-5678

Tags: