
如何用 python 遍历 n 级 json 并以树状打印
问题:
如何遍历并全量打印如下 json 数据中的所有节点,使其呈现树状结构?
{
"id": "series",
"css": "wrapper",
"html": [
{
"id": "series",
"css": "header",
"html": [
{
"css": "topbar",
"html": [
{
"css": "left",
"html": []
},
{
"css": "middle",
"html": []
},
{
"css": "right",
"html": []
}
]
},
{
"css": "mask",
"html": []
},
{
"css": "layer",
"html": []
}
]
},
{
"id": "series",
"css": "container",
"html": [
{
"id": "series",
"css": "container ad1200 mt10",
"html": []
},
{
"id": "series",
"css": "container crumb",
"html": []
},
{
"id": "series",
"css": "container nav",
"html": []
},
{
"id": "series",
"css": "series_wrapper",
"html": [
{
"id": "series",
"css": "main",
"html": [
{
"pic": "",
"total": ""
},
{
"news1": "",
"new2": ""
},
{
"ad1": ""
},
{
"list": ""
},
{
"pic": ""
},
{
"video": ""
},
{
"ad2": ""
}
]
},
{
"id": "series",
"css": "side",
"html": [
{
"ad3": "google"
},
{
"love": ""
},
{
"brand": ""
},
{
"type": ""
}
]
}
]
}
]
},
{
"position": [
{
"return_top": ""
},
{
"side_nav": ""
}
]
},
{
"footer": [
{
"nav": ""
}
]
}
]
}回答:
立即学习“Python免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
要遍历 n 级 json 并以树状打印其所有节点,可以使用以下 python 函数:
def print_json_tree(json_obj, indent=0):
if isinstance(json_obj, dict):
for key, value in json_obj.items():
print('-' * indent + str(key))
print_json_tree(value, indent+2)
elif isinstance(json_obj, list):
for item in json_obj:
print_json_tree(item, indent+2)
else:
print('-' * indent + str(json_obj))该函数以递归的方式遍历 json 对象,使用缩进字符(-)来表示不同的层级。具体过程如下:
通过调用此函数,可以以树状格式遍历并打印 json 对象的全部内容。
以上就是Python如何以树状结构打印多层嵌套JSON数据?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号