如何使用python删除json对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19201233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:07:20  来源:igfitidea点击:

how to delete json object using python?

pythonjson

提问by arglee

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.

我正在使用 python 删除和更新从用户提供的数据生成的 JSON 文件,因此只有少数项目应存储在数据库中。我想从 JSON 文件中删除特定对象。

My JSON file is:

我的 JSON 文件是:

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

I want to delete the JSON object with enamemark.

我想删除 JSON 对象enamemark

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:

由于我是 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

采纳答案by mdml

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

这是一个完整的示例,它加载 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=(',', ': '))
)

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 forloop (you don't want to modify the list while you iterate through it).

主要的一点是我们通过遍历加载列表中的对象来找到对象,一旦找到它,就将对象从列表中弹出。如果您需要删除列表中的多个对象,那么您应该存储要删除的对象的索引,然后在到达for循环末尾后立即将它们全部删除(您不希望在遍历列表时修改列表)。

回答by Ivo

You have a list there with two items, which happen to be dictionaries. To remove the first, you can use list.remove(item)or list.pop(0)or del list[0].

你有一个包含两个项目的列表,它们恰好是字典。要删除第一个,您可以使用list.remove(item)list.pop(0)del list[0]

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

回答by Nikhil

You need to use the jsonmodule. I'm assuming python2. Try this:

您需要使用该json模块。我假设python2。尝试这个:

import json
json_data = json.loads('<json_string>')

for i in xrange(len(json_data)):
  if(json_data[i]["id"] == "mark"):
    del json_data[i]
    break

回答by martineau

Your json file contains in a list of objects, which are dictionaries in Python. Just replace the list with a new one that doesn't have the object in it:

您的 json 文件包含在对象列表中,这些对象是 Python 中的字典。只需用一个没有对象的新列表替换列表:

import json

with open('testdata.json', 'rb') as fp:
    jsondata = json.load(fp)

jsondata = [obj for obj in jsondata if obj['ename'] == 'mark']

print json.dumps(jsondata, indent=4)

回答by LeuX

The proper way to json is to deserialize it, modify the created objects, and then, if needed, serialize them back to json. To do so, use the json module. In short, use <deserialized object> = json.loads(<some json string>)for reading json and <json output> = json.dumps(<your object>)to create json strings. In your example this would be:

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)