2013-09-16 60 views
3

我想用「BoxDet」名稱列出「BoxDet」中的所有元素。其目的是列出這樣的說法:BoxDet:ABC ...使用json lib從Python獲取嵌套JSON的元素

我的JSON的一小部分:

{ 
    "id":1, 
    "name":"BoxH", 
    "readOnly":true, 
    "children":[ 
     { 
     "id":100, 
     "name":"Box1", 
     "readOnly":true, 
     "children":[ 
      { 
       "id":1003, 
       "name":"Box2", 
       "children":[ 
        { 
        "id":1019, 
        "name":"BoxDet", 
        "Ids":[ 
         "ABC", 
         "ABC2", 
         "DEF2", 
         "DEFHD", 
         "LKK" 
         ] 
        } 
       ] 
      } 
     ] 
    } 
    ] 
} 

我的問題是隻是在開始的時候,我不能去,因爲第一更深{} 。 我的代碼...

output_json = json.load(open('root.json')) 
for first in output_json: 
    print first 
    for second in first: 
     print second 

...返回我類似的東西:

readOnly 
r 
e 
a 
d 
O 
n 
l 
y 
children 
c 
h 
i 
l 
d 
r 
e 
n 

...的等等。我甚至無法深入Box1,甚至沒有提到Box2。我正在使用Python 2.7

回答

9

你需要爲這個樹搜索算法:

def locateByName(e,name): 
    if e.get('name',None) == name: 
     return e 

    for child in e.get('children',[]): 
     result = locateByName(child,name) 
     if result is not None: 
      return result 

    return None 

現在你可以使用這個遞歸函數LO美食你想要的元素:

node = locateByName(output_json, 'BoxDet') 
print node['name'],node['Ids'] 
+0

嗨亞倫,@Aaron Digulla,另一個問題。你的解決方案對我來說是一種魅力。我正在嘗試改變你的代碼,以便讓我的結果不是Ids,而是「名稱」值本身。 [http://pastebin.com/MDPv0PND]這是我的json,我想提取SUB,SUBSUB和NAME,並且在使用準鏈作爲鏈時,我不會回到層次結構中以獲取SUBSUB2 ...可以你請把我以某種方式放在正確的軌道上? – jakkolwiek

+0

請提出一個新問題。 –

+0

做了它[http://stackoverflow.com/questions/19031797/extract-the-object-names-from-different-nesting-levels-in-json]。 – jakkolwiek

1

當您嘗試在字典上使用for循環時,沒有任何特別的考慮,您只能得到字典中的鍵。那就是:

>>> my_dict = {'foo': 'bar', 'baz':'quux'} 
>>> list(my_dict) 
['foo', 'baz'] 
>>> for x in my_dict: 
...  print repr(x)  
'foo' 
'baz' 

最平常的事情做的是使用dict.iteritems()

>>> for x in my_dict.iteritems(): 
...  print repr(x) 
('foo', 'bar') 
('baz', 'quux') 

或者你可以爲關鍵自己取的值(在Python 3只dict.items()):

>>> for x in my_dict: 
...  print repr(x), repr(my_dict[x])  
'foo' 'bar' 
'baz' 'quux' 
0

請試試像這樣:

output_json = json.load(open('root.json')) 
if "children" in output_json: 
    children = output_json["children"] 
    if "children" in children: 
    children1 = children["children"] 
    if "children" in children1: 
     children2 = children1["children"] 
     if "name" in children2: 
     name = children2["name"] 
     if "Ids" in children2: 
     ids = children2["Ids"] 
     print name, ids 
1

如果你想通過你的實體的孩子進行迭代,你可以做到以下幾點:

for children in output_json["children"]: 
    #Going down to ID: 100 level 
    for grandchildren in children["children"]: 
     #Going down to ID: 1003 level 
     for grandgrandchildren in grandchildren["children"]: 
      #Going down to ID: 1019 level 
      if grandgrandchildren["name"] == "BoxDet": 
       return "BoxDet" + " ".join(grandgrandchildren["Ids"]) 

不是所涉及的JSON模塊中的數據結構的工作原理或多或少像,你通過訪問值經典詞典關鍵:

my_dict[key] = value 
+0

完美,謝謝!我總是迷路於for-loops ... – jakkolwiek

+0

當您在字典中使用for-in時,它會在字典中的所有鍵上進行迭代。 「鍵入字典」 – Ketouem