如何使用Python将新数据插入JSON文件

时间:2019-02-12 03:55:38

标签: python arrays json

我的python代码有一些问题。 我想将新数据插入json文件

file.json

{
  "datas": [
    {
      "KD": "AC0001",
      "TI": "24",
      "TO": "25",
      "AR": "7.21",
      "SG": "100",
      "DT": "2019-02-12 10:44:10"
    }
  ]
}

我要这样插入新行

 {
      "datas": [
        {
          "KD": "AC0001",
          "TI": "24",
          "TO": "25",
          "AR": "7.21",
          "SG": "100",
          "DT": "2019-02-12 10:44:10"
        },{
          "KD": "AC0001",
          "TI": "23",
          "TO": "21",
          "AR": "7.21",
          "SG": "90",
          "DT": "2019-02-12 10:44:10"
        }
      ]
    }

这是我的代码

        student_data = {"data": []}
        data_holder = student_data["data"]
        counter = 0
        data_holder.append({'KD': 'AC0001','TI': '23','TO': '21','AR': '7.21,'SG': '90','DT': '2019-02-12 10:44:10'})

        with open('file.json') as f:
            data = json.load(f)

        data.update(student_data)


        file_path = 'file.json'
        with open(file_path, 'w') as outfile:
            print("writing file to: ", file_path)
            # HERE IS WHERE THE MAGIC HAPPENS
            json.dump(data, outfile, indent=2, ensure_ascii=False)
        outfile.close()
        print("done")

这实际上是代码更新json文件,而不是插入新数据

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法吗?

import json
new_data = {'KD': 'AC0001', 'TI': '23', 'TO': '21',
            'AR': '7.21', 'SG': '90', 'DT': '2019-02-12 10: 44: 10'}
file_path = 'file.json'
with open(file_path) as f:
    data = json.load(f)
    data['datas'].append(new_data)

    with open(file_path, 'w') as outfile:
        json.dump(data, outfile)