2015-02-17 92 views
1
[ 
     { 
      "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": [] 
     } 
] 

想從根打印所有路徑葉(一個具有空「兒童」)。 如Basic.DeviceInfo.DeviceInfo Form.DeviceInfo Form1中JSON打印從根的所有路徑葉

一切都很好下去,直到DeviceInfo窗體2

當談到DeviceInfo表DeviceInfo形式正在進入圖片 - >Basic.DeviceInfo.DeviceInfo Form.DeviceInfo Table.DeviceInfo Table1。

這不應該發生。相反,我需要Basic.DeviceInfo.DeviceInfo Table.DeviceInfo Table1。

我在哪裏錯了我的代碼。任何解決方案

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) 

回答

3

您正在將您的path = path +dic['name']+'.'設置在您的其他子句中。一旦walk()函數完成遍歷DeviceInfoForm'childrens',它將嘗試遍歷DeviceInfoTable。但是,您的功能已設置路徑爲 Basic.DeviceInfo.DeviceInfoForm.

您需要重新組織您的功能,以便在else:語句中未設置路徑。也許

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

這樣你就傳遞正確的路徑到函數,但沒有明確地設置它。