2011-12-09 55 views
2

我想遍歷每個節點? python中的JSON對象。我想實現像遍歷Python中的JSON

def function(data): 
     for element in data: 
       --- do something---- 
       if (some condition): 
         function(element) 

遞歸函數什麼,我想知道的是我怎麼能找到,如果有問題的元素是另一個對象或只是一個字符串。也就是說,我應該寫什麼而不是上面的代碼中的'某些條件'。就像當我走過一個XML,我檢查它是否有任何使用getchildren()的孩子,如果它有,我遞歸地再次調用函數.....

回答

1

一個很好的Python的方式做到這一點可能是這樣的:

def function(data): 
    try: 
     for element in data: 
     --- do something---- 
     function(element) 
    except TypeError: 
     pass 

做的東西,讓蟒蛇提高如有異常你嘗試迭代一些不可迭代的東西;)

0

您可以使用type(var)函數來檢查元素是否字典或列表。

def recurse(data): 
    for element in data: 
     if type(element) is list or type(element) is dict: 
      recurse(element) 
     else: 
      # do something with element 
      pass 
1

使用type一般在Python中有利於更多的功能isinstance的皺起了眉頭。您也可以使用isinstance測試多種類型的在同一時間:

if isinstance(myVar, (list, tuple)): 
    # Something here. 
+0

爲什麼?爲什麼眉頭皺眉? –