如何使用python删除json对象?
我使用python删除和更新从数据生成的JSON文件由用户提供,因此数据库中只应存储很少的项。我
要从JSON文件中删除特定对象。我的JSON文件是:
[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]
我想删除带有“ename”和“mark”的JSON对象。
由于我是python新手,我试图通过将对象转换为dict来删除它,但是
它不起作用。还有别的办法吗?我试过这个:
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
-
下面是一个完整的例子,加载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”循环的结尾之后(您不想修改在遍历时列出)。