處理JSON數據中的嵌套結構通常需要遞歸地解析和處理數據
json庫。如果沒有安裝,可以使用以下命令安裝:pip install json
nested_json_handler.py的文件,并在其中編寫以下代碼:import json
def nested_json_handler(data):
if isinstance(data, dict):
for key, value in data.items():
print(f"Key: {key}")
nested_json_handler(value)
elif isinstance(data, list):
for index, value in enumerate(data):
print(f"Index: {index}")
nested_json_handler(value)
else:
print(f"Value: {data}")
if __name__ == "__main__":
json_string = '''
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": [
"reading",
{
"type": "sports",
"name": "basketball"
},
[1, 2, 3]
]
}
'''
json_data = json.loads(json_string)
nested_json_handler(json_data)
在這個示例中,我們定義了一個名為nested_json_handler的函數,該函數接受一個參數data。首先,我們檢查data是否為字典類型。如果是,我們遍歷字典中的每個鍵值對,并遞歸地調用nested_json_handler函數處理值。如果data是列表類型,我們遍歷列表中的每個元素,并遞歸地調用nested_json_handler函數處理元素。如果data既不是字典也不是列表,我們直接打印其值。
Key: name
Value: John
Key: age
Value: 30
Key: city
Value: New York
Key: hobbies
Index: 0
Value: reading
Index: 1
Key: type
Value: sports
Index: 1
Key: name
Value: basketball
Index: 2
Value: 0
Value: 1
Value: 2
這個示例展示了如何處理JSON數據中的嵌套結構。你可以根據需要修改這個腳本,以適應你的具體需求。