我正在使用 python 删除和更新根据用户提供的数据生成的 JSON 文件,因此数据库中只应存储少量项目。我想从 JSON 文件中删除特定对象。
我的 JSON 文件是:
[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]
我想删除带有 ename
mark
的 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
最佳答案
这是一个完整的示例,它加载 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
的末尾后立即将它们全部删除> 循环(您不想在遍历列表时修改列表)。
关于python - 如何使用python删除json对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19201233/