python - 如何使用python删除json对象?

标签 python json

我正在使用 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/

相关文章:

python - pip 安装 ortools : No matching distribution - Alpine

python - 如何使用 python 元组进行 IN 查询

python - 应用程序启动失败,因为它的并行配置不正确 (Python/Pyinstaller/Tkinter)

json - 从 bigquery WebUI 将 JSON 加载到 bigquery 表时在模式中定义数组

Java 和 XSS : How to html escape a JSON string to protect against XSS?

python - 部署在 Apache 上时,使用带有相对路径的 webpy 的 web.template.render()

python - 如何在Python中获取列表的一部分而不创建新列表?

java - 如何在 JSONObject 中处理来自 RESTful API 的 `null` 字符串?

javascript - 仅当从 angularJS 中的 ajax 调用完全接收到 json 时才更新 View

json - Microsoft Azure dll 在 .NET 4.0 中引发异常