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

时间:2020-01-07 12:18:38

标签: python json

我已经完成研究,但找不到有效的答案。

我有以下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删除它们?

先谢谢了。

2 个答案:

答案 0 :(得分:1)

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

  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)

(注意:此“删除”匹配的所有项,而不仅仅是代码中的第一个)。

另外,您可能希望在完成处理后保存,而不是在处理期间保存。

答案 1 :(得分:0)

由于它是一个列表,因此您可以在列表中找到与价格输入相匹配的索引值。然后从'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)