在每个函数调用中,我想将一个新字典添加到json文件并将所有内容保存到更新的文件中。
基本上,我想创建一个json文件,该函数每次执行时都会使用新顺序的信息进行更新。
我遵循的过程是这样:
问题是,似乎每次迭代都会覆盖结果
我写的代码是这样的:
import json
from pathlib import Path
def exportOrderJson(filename,ordine,data,status,business,product,quantity,amount):
filename += ".json"
JSON_PATH = Path(filename)
# If file not exists, I create it and inizialize
if (not(JSON_PATH.is_file())):
order_dict_inizialize = {"Orders": {}}
with open(filename, 'w') as outfile:
json.dump(order_dict_inizialize, outfile, indent=2)
# New dict to append
order_dict = {
"order_id": ordine,
"data": data,
"status": status,
"is_business": business,
"quantity": quantity,
"amount": amount
}
# json object to python object
with open(filename,"r") as json_file:
obj = json.load(json_file)
# I update the python dict with the new dict
obj["Orders"].update(order_dict)
# I write the updated dict to the json file
with open(filename, 'w') as outfile:
json.dump(obj, outfile, indent=2)
# Execute function
for i in range(3):
exportOrderJson(........)
文件输出为:
{
"Orders": {
"order_id": "3",
"data": "xxx",
"status": "xxx",
"is_business": "xxx",
"quantity": "xxx",
"amount": "xxx"
}
}
我想要的是:
{
"Orders": {
"order_id": "1",
"data": "xxx",
"status": "xxx",
"is_business": "xxx",
"quantity": "xxx",
"amount": "xxx"
},
{
"order_id": "2",
"data": "xxx",
"status": "xxx",
"is_business": "xxx",
"quantity": "xxx",
"amount": "xxx"
},
{
"order_id": "3",
"data": "xxx",
"status": "xxx",
"is_business": "xxx",
"quantity": "xxx",
"amount": "xxx"
},
}