如何使用python从JSON文件中删除空{}

2024-10-01 04:56:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经做了研究,但找不到任何有效的答案

我有以下JSON文件:

{
    "Cars": [{
            "Manufacturer": "Audi",
            "model": "R8",
            "price": 50000,
            "a": {
                "n": "1",
                "street": "ABC Street",
                "city": "London",
                "postcode": "TW1 1AA"
            }
        },
        {
            "Manufacturer": "Ford",
            "model": "Fiesta",
            "price": 10000,
            "a": {
                "n": 2,
                "street": "DEF street",
                "town": "London",
                "PostCode": "TW2 2AB"
            }
        },
        {
            "Manufacturer": "VW",
            "model": "Polo",
            "price": 5000,
            "a": {
                "n": "3",
                "Street": "GHI Street",
                "town": "London",
                "postcode": "TW3 3CD"
            }
        }

    ]
}

在我的python文件中,要删除JSON元素,我使用以下命令:

deletecar = int(input("Enter price of car to delete: "))
for item in data["Cars"]:
   if deletecar == item["price"]:
      item.pop("Manufacturer")
      item.pop("model")
      item.pop("price")
      item.pop("a")

      with open("testjson.json", 'w') as f:
          json.dump(data, f)

运行此操作时,如果删除JSON文件中的第一辆车,我会发现:

{"Cars": [{}, {"Manufacturer": "Ford", ...

如果我现在再次运行我的程序,但我尝试搜索汽车,由于这些空括号,程序将无法工作

那么如何使用Python删除它们呢

提前谢谢


Tags: 文件jsonstreetmodelitemcarspopprice
2条回答

由于它是一个列表,您可以在列表中找到与您的价格输入匹配的索引值。然后从'Cars'列表中的值中删除这些元素

deletecar = int(input("Enter price of car to delete: "))

# Get the index values of where the item is located
index_to_delete = []
for item in data["Cars"]:
   if deletecar == item["price"]:
      index_to_delete.append(data["Cars"].index(item))

# Since the index values will change as you delete them,
# you will have to remove them in reverse order (in case there's more than 1 
# item being removed

for i in reversed(index_to_delete):
    del data["Cars"][i]      

# write to file      
with open("testjson.json", 'w') as f:
    json.dump(data, f)

您需要删除项目本身,这意味着您需要两个步骤:

  1. 查找要删除的项所在的索引
  2. 从列表中删除该项(使用del

你不需要“清空”口述,因为那不是你要找的

或者,您可以使用列表理解filter调用创建一个全新的列表,而不包含有问题的项目,例如

deletecar = int(input("Enter price of car to delete: "))
data['Cars'] = [
    item for item in data['Cars']
    if item['price'] != deletecar
]

with open("testjson.json", 'w') as f:
      json.dump(data, f)

(注意:这将“删除”所有匹配的项,而不是像代码那样仅删除第一项)

另外,您可能希望在完成处理后保存,而不是在处理过程中保存

相关问题 更多 >