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

作者站长头像
站长
· 阅读数 10

如题,是要遍历显示全

比如要遍历显示以下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":""}
    ] }
]

}

回复
1个回答
avatar
test
2024-07-04

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

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)
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容