Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
如何用Python遍历N级JSON并生成树状结构?_创想鸟

如何用Python遍历N级JSON并生成树状结构?

如何用python遍历n级json并生成树状结构?

遍历 n 级 json,生成树结构

本文档将介绍如何使用 python 遍历嵌套 json 数据,并将其转换为树状结构。

python 方案

python 提供了多种方法来遍历复杂 json 对象。例如,使用 json.loads() 将 json 字符串加载为 python 数据结构:

立即学习“Python免费学习笔记(深入)”;

import jsonjson_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并生成树状结构?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1354214.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
MongoDB 能否胜任复杂的企业业务报表制作?
上一篇 2025年12月13日 18:22:06
Python多进程监听同一端口失败:为何线程池无法绑定相同端口?
下一篇 2025年12月13日 18:22:19

相关推荐

发表回复

登录后才能评论
关注微信