我有一个JSON文件(test.json),它有一个列表:
[
{
"Action": "ADD",
"Properties": {
"Type": "New",
"Value": "List"
}
},
{
"Action": "REMOVE",
"Properties": {
"Type": "New",
"Value": "Image"
}
},
{
"Action": "ADD",
"Properties": {
"Type": "New",
"Value": "Text"
}
}
]
我需要遍历列表并删除包含'REMOVE‘的键(item),即item’‘Action’== "REMOVE“。
删除后应如下所示:
[
{
"Action": "ADD",
"Properties": {
"Type": "New",
"Value": "List"
}
},
{
"Action": "ADD",
"Properties": {
"Type": "New",
"Value": "Text"
}
}
]
我用它来打印项目。如何删除该项目?
with open('test.json') as json_data:
data = json.load(json_data)
for item in data:
if item['Action'] == "REMOVE":
print item
发布于 2018-07-20 05:34:53
当你需要过滤列表时,你应该使用列表理解:
with open('test.json') as json_data:
data = json.load(json_data)
filtered_data = [item for item in data if item['Action'] != 'REMOVE']
发布于 2018-07-20 23:18:05
我最终使用了这个:
with open('test.json') as json_data:
data = json.load(json_data)
for index, item in enumerate(data):
if item['Action'] == "REMOVE":
del( data[index] )
with open('test.json', "w") as outfile:
outfile.write(json.dumps(data, indent=4))
发布于 2018-07-20 05:38:11
data = [x for x in json_data if not x['ACTION'] == 'REMOVE']
获取只包含所需项目的新列表的另一种方法。
https://stackoverflow.com/questions/51431974
复制相似问题