如何用Python遍历N级JSON并生成树状结构?
“纵有疾风来,人生不言弃”,这句话送给正在学习的朋友们,也希望在阅读本文《如何用Python遍历N级JSON并生成树状结构?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新文章相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

遍历 n 级 json,生成树结构
本文档将介绍如何使用 python 遍历嵌套 json 数据,并将其转换为树状结构。
python 方案
python 提供了多种方法来遍历复杂 json 对象。例如,使用 json.loads() 将 json 字符串加载为 python 数据结构:
import json
json_str = '''
{
"id": "series",
"css": "wrapper",
"html": [
{ "id": "series", "css": "header", "html": "..." }
# ...
]
}
'''
json_obj = json.loads(json_str)
要遍历嵌套数据,可以使用递归函数,根据数据类型(字典或列表)进行不同的递归调用:
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 对象的树状结构示例:
- id
- css
- html
- id
- css
- topbar
- mask
- layer
- id
- css
- html
- id
- css
- html
- pic
- total
- news1
- new2
- ad1
- list
- pic
- video
- ad2
- id
- css
- ad3
- love
- brand
- type
- position
- return_top
- side_nav
- footer
- nav
本篇关于《如何用Python遍历N级JSON并生成树状结构?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注米云公众号!
