可以使用递归来遍历嵌套JSON对象。以下是一个示例代码:
def loop_through_nested_json(json_obj):
if isinstance(json_obj, dict):
for key in json_obj:
value = json_obj[key]
if isinstance(value, (dict, list)):
loop_through_nested_json(value)
else:
print(key, ":", value)
elif isinstance(json_obj, list):
for item in json_obj:
loop_through_nested_json(item)
使用上述函数,可以遍历任何嵌套JSON对象并打印出其键和值。例如:
json_obj = {
"name": "John",
"age": 30,
"hobbies": ["reading", "music"],
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
}
loop_through_nested_json(json_obj)
将输出以下内容:
name : John
age : 30
hobbies : reading
hobbies : music
street : 123 Main St
city : New York
state : NY