Python 删除对象数组中的 JSON 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19167485/
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:02:51  来源:igfitidea点击:

Removing JSON property in array of objects

pythonjson

提问by Evan Emolo

I have a JSON array that I'm cleaning up in Python. I want to remove the imageDataproperty:

我有一个正在用 Python 清理的 JSON 数组。我想删除该imageData属性:

data.json

数据.json

[{"title": "foo", "imageData": "xyz123"},
{"title": "bar", "imageData": "abc123"},
{"title": "baz", "imageData": "def456"}]

I am setting up a list comprehension to remove the property, but I'm not sure how to create the variable that focuses on imageData:

我正在设置一个列表理解来删除该属性,但我不确定如何创建关注的变量imageData

import json

with open('data.json') as json_data:
    data = json.load(json_data)
    clean_data = [ item for item in data if not item['imageData'] ]
    # Write `clean_data` to new json file

When I printthe list comprehension, it returns an empty array. What do I have to correct to get this working properly?

当我print进行列表理解时,它返回一个空数组。我需要纠正什么才能使其正常工作?

采纳答案by Stefano Sanfilippo

An easy solution to your problem is deleting the unwanted key in place, with del:

解决问题的一个简单方法是删除不需要的密钥,使用del

import json

with open('data.json') as json_data:
    data = json.load(json_data)
    for element in data: 
        del element['imageData'] 

You should add some safety checks, but you get the idea.

您应该添加一些安全检查,但您明白了。

回答by Evan Emolo

[ item for item in data if not item['imageData'] ]

is empty becaus allhave imageData. You are just testingfor it, not removingit.

为空,因为...一切都有imageData。您只是在测试它,而不是删除它。

Loop over dateand del item['imageData']on each item.

遍历datedel item['imageData']在每个item

回答by Daniel Roseman

If not all the elements have an imageDatakey, then using delwill cause an KeyErrorexception. You could guard against that by using popwith a default:

如果不是所有的元素都有一个imageData键,那么使用del会导致KeyError异常。您可以通过使用pop默认值来防止这种情况:

for item in data: 
    item.pop('image', None)

回答by wwii

How about:
clean_data = [k:v for k,v in data.iteritems() if k != 'imageData']

怎么样:
clean_data = [k:v for k,v in data.iteritems() if k != 'imageData']

Or a dictionary expresion/comprehension if you want a dictionary:
clean_data = {k:v for k,v in data.iteritems() if k != 'imageData'}

如果你想要一本字典,或者一个字典表达式/理解:
clean_data = {k:v for k,v in data.iteritems() if k != 'imageData'}