python删除json数组数据,如何使用python删除json对象?

I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the JSON file.

My JSON file is:

[

{

"ename": "mark",

"url": "Lennon.com"

},

{

"ename": "egg",

"url": "Lennon.com"

}

]

I want to delete the JSON object with ename mark.

As I am new to python I tried to delete it by converting objects into dict but it is not working. Is there any other way to do it?

i tried this one:

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

解决方案

Here's a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.

#!/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=(',', ': '))

)

The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you've reached the end of the for loop (you don't want to modify the list while you iterate through it).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值