shishao723
小石头723
采纳率100%
2018-05-04 10:45

使用Python或Java解析Json文件,逐级打印菜单

20
已采纳

有这样一个菜单json文件:
{"id":"100"
"name":"File"
"parent":"#",

"id":"200"
"name":"Edit"
"parent":"#",

"id":"300"
"name":"Search"
"parent":"#",

"id":"400"
"name":"Project"
"parent":"#",

"id":"500"
"name":"Help"
"parent":"#",

"id":"101"
"name":"New"
"parent":"100",

"id":"102"
"name":"Open"
"parent":"100",

"id":"103"
"name":"Load"
"parent":"100",

"id":"201"
"name":"Cut"
"parent":"200",

"id":"202"
"name":"Copy"
"parent":"200",

"id":"203"
"name":"Paste"
"parent":"200",

"id":"301"
"name":"Back"
"parent":"300",

"id":"302"
"name":"Replace"
"parent":"300",

"id":"303"
"name":"Jump"
"parent":"300",

"id":"401"
"name":"Add"
"parent":"400",

"id":"402"
"name":"Remove"
"parent":"400",

"id":"403"
"name":"Close"
"parent":"400",

"id":"501"
"name":"Mode"
"parent":"500",

"id":"502"
"name":"Key"
"parent":"500",

"id":"503"
"name":"About"
"parent":"500",

"id":"1011"
"name":"xx"
"parent":"101",

"id":"2011"
"name":"yy"
"parent":"201",

"id":"3011"
"name":"zz"
"parent":"301",
}

想要打印出如下结果:

100 File 100 File
101 New 100>101 File>New
1011 xx 100>101>1011 File>New>xx
102 Open 100>102 File>Open
103 Load 100>103 File>Load
200 Edit 200 Edit
201 Cut 200>201 Edit>Cut
2011 yy 200>201>2011 Edit>Cut>yy
202 Copy 200>202 Edit>Copy
203 Paste 200>203 Edit>Paste
300 Search 300 Search
301 Back 300>301 Search>Back
3011 zz 300>301>3011 Search>Back>zz
302 Replace 300>302 Search>Replace
303 Jump 300>303 Search>Jump
400 Project 400 Project
401 Add 400>401 Project>Add
402 Remove 400>402 Project>Remove
403 Close 400>403 Project>Close
500 Help 500 Help
501 Mode 500>501 Help>Mode
502 Key 500>502 Help>Key
503 About 500>503 Help>About

想要得出如下结果:
属性Parent如果为#时,说明这是一个根节点,直接打印,打印格式为 ID+Name+ID+Name
属性Parent如果非#时,则需要找到父节点的ID和Name,打印格式为 ID+Name+Parent ID>ID+Parent Name>Name
如果父节点也不是一个根节点,打印格式为 ID+Name+根节点ID>Parent ID>ID+根节点Name>Parent Name>Name,以此类推。当菜单层级非常多时,此处判断如何写一个递归算法,逐级找到某节点的所有父节点。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • devmiao devmiao 3年前
     python 递归解析json
    
    import json
    def parse(js):
        for key in js.keys():
            if isinstance(js.get(key),dict):
                parse(js.get(key))
            elif isinstance(js.get(key),list):
                parse(js.get(key))
            else:
                print 'key:%s->value:%s'%(key,js.get(key))
    
    点赞 1 评论 复制链接分享
  • devmiao devmiao 3年前
    点赞 评论 复制链接分享

相关推荐