如何用 python 深入遍历 json 结构,按树结构打印?
在处理复杂多层的 json 数据时,按层次结构打印其内容会更有条理和可读性。
问题:
本文提供了一个 json 结构,需要将其所有节点深度遍历并按树结构打印出来。
答案:
为了实现嵌套 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 结构:
{ "id": "series", "css": "wrapper", "html": [ {"id": "series","css": "header","html": [ { "css": "topbar", "html": [] }, { "css": "mask", "html": [] }, { "css": "layer", "html": [] }] }, {"id": "series","css": "container","html": [] }, {"position": [] }, {"footer": [] } ]}
输出结果:
-id–series-css–wrapper-html–0—id—-series—css—-header—html—-0—–css——topbar—–html——-""—-1—–css——mask—–html——-""—-2—–css——layer—–html——-""–1—id—-series—css—-container—html——-""–2—position——-""–3—footer——-""
以上就是如何用Python递归打印JSON树状结构?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » 如何用Python递归打印JSON树状结构?