深度阅读

How to parse nested JSON objects in Python?

作者
作者
2023年08月22日
更新时间
14.51 分钟
阅读时间
0
阅读量

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

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。