如何使用python删除json对象? [英] how to delete json object using python?

查看:1076
本文介绍了如何使用python删除json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python删除和更新根据用户提供的数据生成的JSON文件,因此数据库中应仅存储少量项目.我想从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.

我的JSON文件是:

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

我想用ename mark删除JSON对象.

I want to delete the JSON object with ename mark.

由于我是python的新手,所以我尝试通过将对象转换为dict来删除它,但它不起作用.还有其他方法吗? 我尝试了这个:

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

推荐答案

下面是一个完整的示例,该示例加载JSON文件,删除目标对象,然后将更新的JSON对象输出到文件.

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

主要要点是,我们通过遍历已加载列表中的对象来找到对象,然后在找到对象后将其从列表中弹出.如果需要删除列表中的多个对象,则应存储要删除的对象的索引,然后在到达for循环结束时立即将其全部删除(不要您不想在遍历列表时修改它.)

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).

这篇关于如何使用python删除json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆