2013-10-05 321 views
5

我正在使用python刪除和更新從用戶提供的數據生成的JSON文件,以便只有少數項目應該存儲在數據庫中。我想從JSON文件中刪除一個特定的對象。如何使用python刪除json對象?

我的JSON文件是:

[ 
    { 
     "ename": "mark", 
     "url": "Lennon.com" 
    }, 
    { 
     "ename": "egg", 
     "url": "Lennon.com" 
    } 
] 

我想enamemark刪除的JSON對象。

由於我是新的python,我試圖通過將對象轉換爲字典來刪除它,但它不工作。有沒有其他方法可以做到這一點? 我想這一個:

index=0 
while index < len(data): 
    next=index+1 
    if(data[index]['ename']==data[next]['ename']): 
     print "match found at" 
     print "line %d and %d" %(next,next+1) 
     del data[next] 
    index +=1 
+2

你能告訴我們你試過的代碼嗎? – RyPeck

+0

@RyPeck是的我編輯我的問題與我試着的代碼.. – arglee

+0

當你運行這個,你有問題,因爲該文件沒有改變? – RyPeck

回答

11

下面是加載JSON文件的完整範例,刪除目標對象,然後輸出更新JSON對象到文件。

#!/usr/bin/python                

# Load the JSON module and use it to load your JSON file.      
# I'm assuming that the JSON file contains a list of objects.     
import json 
obj = json.load(open("file.json")) 

# Iterate through the objects in the JSON and pop (remove)      
# the obj once we find it.              
for i in xrange(len(obj)): 
    if obj[i]["ename"] == "mark": 
     obj.pop(i) 
     break 

# Output the updated file with pretty JSON          
open("updated-file.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) 
) 

主要的一點是,我們發現通過在加載列表中的對象迭代對象,然後在彈出的對象從名單一旦我們找到它。如果您需要刪除列表中的多個對象,則應存儲要刪除的對象的索引,並在到達for循環結束時立即將其全部刪除(不要想要在遍歷它時修改列表)。

+0

它不起作用。當我跑它時,它沒有從列表中彈出標記 – arglee

+1

嗯,我用你的確切輸入運行該腳本,標記被刪除。該腳本正在輸出到一個名爲''updated-file.json''的新文件,因此它不會更新原始文件。也許這就是發生了什麼? – mdml

+0

我實際上粘貼了你的代碼,但它仍然不起作用。它是生產同一個文件中以前 – arglee

0

你有兩個項目,這正好是字典有一個列表。要刪除第一個,您可以使用list.remove(item)list.pop(0)del list[0]

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

+0

@lvo thanx但list.remove(0)將從列表中刪除第一項。我想從那裏刪除整個對象。 – arglee

+0

@ user2511142 http://ideone.com/NlCTSp – Ivo

+0

是的,但它不在這裏工作,並顯示錯誤,'文件'不支持刪除項目 – arglee

0

您需要使用json模塊。我假設python2。試試這個:

import json 
json_data = json.loads('<json_string>') 

for i in xrange(len(json_data)): 
    if(json_data[i]["id"] == "mark"): 
    del json_data[i] 
    break 
+2

如果字典處於*不同的位置,該怎麼辦? –

+0

感謝名單@MartijnPieters但我已經嘗試過這...這是行不通的.. – arglee

+0

@MartijnPieters公平點。我已經更新了我的答案以進行線性搜索。 – Nikhil

0

你的json文件包含一個對象列表,它是Python中的字典。只需更換一個新的,沒有對象在其列表:

import json 

with open('testdata.json', 'rb') as fp: 
    jsondata = json.load(fp) 

jsondata = [obj for obj in jsondata if obj['ename'] == 'mark'] 

print json.dumps(jsondata, indent=4) 
2

到JSON的正確方法是反序列化,修改創建的對象,然後,如果需要的話,它們序列回JSON。 爲此,請使用the json module。總之,使用<deserialized object> = json.loads(<some json string>)來閱讀json和<json output> = json.dumps(<your object>)來創建json字符串。 在你的例子中這將是:

import json 
o = json.loads("""[ 
    { 
     "ename": "mark", 
     "url": "Lennon.com" 
    }, 
    { 
     "ename": "egg", 
     "url": "Lennon.com" 
    } 
]""") 
# kick out the unwanted item from the list 
o = filter(lambda x: x['ename']!="mark", o) 
output_string = json.dumps(o) 
+1

它怎麼會這麼簡單?!最佳答案! – Minoru