【问题标题】:How to Insert new data to JSON file with Python如何使用 Python 将新数据插入 JSON 文件
【发布时间】:2019-02-12 03:55:37
【问题描述】:

我的 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 文件,而不是插入新数据

【问题讨论】:

  • 我是 Java 人,但我在这里看不到任何 Java 代码 -- 为什么是 Java 问题标签?
  • 为什么不直接删除第一行,然后将脚本顶部的json 加载为student_data = json.load(f)
  • 修复data_holder.append(.... 行中的语法错误。就连 SO 的语法高亮也会告诉你它坏了……

标签: python arrays json


【解决方案1】:

您可以尝试以下方法吗:

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)

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多