【发布时间】:2023-03-16 19:44:01
【问题描述】:
我有这个 JSON
{"data":
[
{
"id": "11111",
"description": "Description 1",
"to_remove": "blah",
"state": "Assigned"
},
{
"id": "2222",
"description": "Description 2",
"to_remove": "blah"
},
{
"id": "33333",
"description": "Description 3",
"to_remove": "blah",
"state": "Assigned"
}
]}
我需要删除“状态”不存在的所有对象并删除单个键 (to_remove) 才能获得此输出:
{"data":
[
{
"id": "11111",
"description": "Description 1",
"state": "Assigned"
},
{
"id": "33333",
"description": "Description 3",
"state": "Assigned"
}
]}
我尝试使用此代码:
json_data = json.loads(data)
for element in json_data['data']:
if 'state' in element:
del element['to_remove']
else:
del element
但是输出是这样的:
{"data":
[
{
"id": "11111",
"description": "Description 1",
"state": "Assigned"
},
{
"id": "2222",
"description": "Description 2"
"to_remove": "blah",
},
{
"id": "33333",
"description": "Description 3",
"state": "Assigned"
}
]}
我可以删除单个键,但不能删除所有元素。 del 元素 命令不返回错误。 如果我在 del 元素 之后使用 del 元素['to_remove'] 我有错误“名称元素不存在”
【问题讨论】: