如何用python遍历n级json,向树结构一样列印?

如何用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":""}

] }

]

}


回答:

你没有给树结构的例子,试试这个。

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_str = '''

{

"name": "John",

"age": 30,

"city": "New York",

"pets": [

{

"name": "Fluffy",

"type": "cat"

},

{

"name": "Fido",

"type": "dog"

}

]

}

'''

json_obj = json.loads(json_str)

print_json_tree(json_obj)

以上是 如何用python遍历n级json,向树结构一样列印? 的全部内容, 来源链接: utcz.com/p/938883.html

回到顶部