如何将dict附加到python中的dict并导出到json文件

时间:2020-09-09 11:06:31

标签: python json

在每个函数调用中,我想将一个新字典添加到json文件并将所有内容保存到更新的文件中。

基本上,我想创建一个json文件,该函数每次执行时都会使用新顺序的信息进行更新。

我遵循的过程是这样:

  1. 我将json文件加载到python对象中
  2. 我将新订单添加到python对象
  3. 我用新的python对象重写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"
  },
}

0 个答案:

没有答案