
遍历 n 级 json,生成树结构
本文档将介绍如何使用 python 遍历嵌套 json 数据,并将其转换为树状结构。
python 方案
python 提供了多种方法来遍历复杂 json 对象。例如,使用 json.loads() 将 json 字符串加载为 python 数据结构:
立即学习“Python免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
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并生成树状结构?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号