JSON prints all the way from root to leaf

[ { "name": "Basic", "id": "home", "childrens": [ { "name": "Dashboard", "viewtype": "custom", "view": "dashboard.html", "childrens": [] }, { "name": "DeviceInfo", "href": "WSettings", "childrens": [ { "name": "DeviceInfo Form", "childrens": [ { "name": "DeviceInfo Form1", "viewtype": "xml", "view": "dinfo", "childrens": [] }, { "name": "DeviceInfo Form2", "viewtype": "xml", "view": "complexjson", "childrens": [] } ] }, { "name": "DeviceInfo Table", "childrens": [ { "name": "DeviceInfo Table1", "viewtype": "xml", "view": "dinfotable", "childrens": [] }, { "name": "DeviceInfo Table2", "viewtype": "xml", "view": "jsontable", "childrens": [] } ] } ] }, { "name": "Hybrid", "childrens": [ { "name": "Table-Form", "viewtype": "xml", "view": "hybrid", "childrens": [] } ] } ] }, { "name": "Advanced", "id": "profile", "childrens": [] } ] 

Want to print all the way from root to leaf (one with empty 'childrens' ). For example, Basic.DeviceInfo.DeviceInfo Form.DeviceInfo Form1

Everything is going fine while DeviceInfo Form2

When it comes to the DeviceInfo Table, the DeviceInfo Form goes into the image - > Basic.DeviceInfo.DeviceInfo Formats Table..DeviceInfo Table1.

It should not be. Instead, I need Basic.DeviceInfo.DeviceInfo Table.DeviceInfo Table1.

Where am I wrong in my code. Any solution?

 def walk(list1, path = ""): for dic in list1: #print('about to walk', dic['name'], 'passing path -->', path) if(len(dic['childrens']) == 0): print('leaf --->', path+dic['name']+'.') else: path = path+dic['name']+'.' #passing parent name to childreni walk(dic['childrens'], path) 
+1
source share
1 answer

You set your path = path +dic['name']+'.' in his else clause. After the walk() function completes the move through the child devices of DeviceInfoForm, it tries to traverse DeviceInfoTable. However, your function has already set the path to Basic.DeviceInfo.DeviceInfoForm.

You need to reorganize your function so that the path is not set in the else: . Maybe,

 else: walk(dic['childrens'], path+dic['name']+'.') 

This way you pass the correct path to the function, but do not explicitly set it.

+3
source

Source: https://habr.com/ru/post/1237224/


All Articles