[英]How to remove empty { } from JSON file using 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 刪除它們呢?
提前致謝。
您需要刪除項目本身,這意味着您需要兩個步驟:
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)
(注意:這會“刪除”所有匹配的項目,而不僅僅是您的代碼所做的第一個項目)。
此外,您可能希望在完成處理后保存,而不是在處理期間保存。
由於它是一個列表,您可以在列表中找到與您輸入的價格相匹配的索引值。 然后從'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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.