2014-11-17 57 views
-3

我目前在使用python 2.7解決這個問題時遇到了麻煩。基本上我需要檢查父節點內是否存在子節點。如果是,那麼只需打印鍵和值,如果不是,則使用鍵和值插入子節點。Python:在JSON中查找節點,如果沒有,則進入節點

JSON的結構是這樣的:

{ 
"Movies": { 
    "Drama": { 
     "main": { 
      "actor": "MR x", 
      "actress": "Miss Y" 
     } 
    }, 
    "Action": { 
     "Aux": { 
      "director": "MR J", 
      "Producer": "Mr K" 
     }, 
     "main": { 
      "actor": "MR yyyy", 
      "actress": "Mrs XXXX" 
     } 
    } 
    }, 

    "Serial":{------- 
    ................... 
    } 
} 

在上面的JSON結構,我需要首先檢查子節點「AUX」的存在與否,如果沒有的話,我需要添加的整個街區,

 "Aux": { 
      "director": "MR J", 
      "Producer": "Mr K" 
     }, 

裏面的「Action」節點。 我怎麼能做到這一點,到目前爲止,我已經做到了這一點,

try: 
    json_file = ('record.json') 
    with open(json_file,'r+') as data_file:  
     data = json.load(data_file) 
     for item in parent: 

except Exception, e: 
    print e 

我怎樣才能解決這個問題?

在此先感謝。

+0

你只需要檢查在'Movies'子節點,對不對? –

+0

好吧,詳細一點,有更多的節點,如「連載」,「紀錄片」等,電影是其中之一。 ***我已編輯問題 – Nepal12

回答

1

你分割你的問題分爲兩個步驟。讀寫。 在第一步中,您可以檢查'Aux``是否已經在鍵中。如果沒有,請添加它。 然後你只需打開文件中寫入和清理數據寫入到它:

import json 

with open("record.json", "r") as infile: 
    data = json.load(infile) 
    for genre in data: 
     for movie_genre in data[genre]: 
      if "Aux" not in data[genre][movie_genre].keys(): 
       data[genre][movie_genre]["Aux"] = {"director": "MR J", "Producer": "Mr K"} 

with open("record.json", "w") as outfile: 
    outfile.write(json.dumps(data, indent=2)) 
+0

完美的,非常感謝你的方法是最好的,並已解決我的問題 – Nepal12

+0

有一個小故障,如果找到節點「AUX」,然後,我試圖打印,但不知何故反應打印超過20次。爲什麼這樣?和我怎樣才能擺脫它 – Nepal12

+0

你將不得不顯示您的更新的代碼爲我瞭解 –

0

您可以檢查輔助是否是JSON字典可用,如果沒有,你可以添加:

try: 
    json_file = ('record.json') 
    with open(json_file,'r+') as data_file:  
     data = json.load(data_file) 
     if 'Aux' not in data: 
      data['Movies']['Action']['Aux'] = {"director": "MR J", "Producer": "Mr K"} 

except Exception, e: 
    print e 
+0

這是硬編碼的方式,雖然... –

+0

但我確實回答了這個問題。硬代碼部分總是可以參數化或變化的。 –