我使用python来删除和更新用户提供的数据生成的JSON文件,因此只有少数项目应存储在数据库中.我想从JSON文件中删除一个特定的对象.
我的JSON文件是:
[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]
Run Code Online (Sandbox Code Playgroud)
我想删除JSON对象ename mark.
因为我是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
Run Code Online (Sandbox Code Playgroud)
mdm*_*dml 14
这是一个完整的示例,它加载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=(',', ': '))
)
Run Code Online (Sandbox Code Playgroud)
重点是我们通过迭代加载列表中的对象来找到对象,然后在找到对象后将对象从列表中弹出.如果您需要删除列表中的多个对象,那么您应该存储要删除的对象的索引,然后在到达for循环结束后立即将它们全部删除(您不想要在迭代它时修改列表).
json的正确方法是反序列化,修改创建的对象,然后根据需要将它们序列化回json。为此,请使用json模块。简而言之,<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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38165 次 |
| 最近记录: |