如何用 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": "" }] } ]}
回答:
要遍历 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 对象,使用缩进字符(-)来表示不同的层级。具体过程如下:
- 如果当前对象是字典(dict),遍历其键和值,并将值作为新的一层进行遍历。如果当前对象是列表(list),遍历列表中的每个元素,并将元素作为新的一层进行遍历。如果当前对象是标量类型(字符串、整数、浮点数等),则直接打印出来。
通过调用此函数,可以以树状格式遍历并打印 json 对象的全部内容。
以上就是Python如何以树状结构打印多层嵌套JSON数据?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » Python如何以树状结构打印多层嵌套JSON数据?