我正在处理问题。我只想通过found属性删除JSON项目,这里是Json:
{"name": "Nike shirt", "price": "20", "size": "M", "additionalInfo": "best shirt ever", "gender": "male", "itemType": "shirts"}
{"name": "adidas airmax", "price": "30", "size": "40", "additionalInfo": "best shoe ever", "gender": "male", "itemType": "running shoes"}
这里是删除方法:
@staticmethod
def deleteFromCart(cartJson,searchAttribute):
for item in Item.jsonOpener(cartJson):
if(item.getName == searchAttribute):
del item
with open(cartJson, "w") as filelines:
for item in Item.jsonOpener(cartJson):
jsonString = json.dumps(item.__dict__)
filelines.write(jsonString + "\n")
例如,我想删除“ Nike衬衫”:Item.deleteFromCart(“ items.json”,“ Nike衬衫”),但它删除了我的所有内容。谢谢您的回答。
我希望
{"name": "adidas airmax", "price": "30", "size": "40", "additionalInfo": "best shoe ever", "gender": "male", "itemType": "running shoes"}
您正在尝试读写同一文件同时:
with open(cartJson, "w") as filelines: # here you open file for writing, which destroys contents
for item in Item.jsonOpener(cartJson): # and here you try to read the contents that no longer exist
您应该首先将文件读入变量,然后打开文件进行写,然后将数据写回:
def deleteFromCart(cartJson,searchAttribute):
data = []
for item in Item.jsonOpener(cartJson):
if item.getName() != searchAttribute:
# DON'T store the item you want deleted
jsonString = json.dumps(item.__dict__)
data.append(jsonString)
with open(cartJson, "w") as filelines:
for line in data:
filelines.write(line + "\n")