通过Python脚本将对象数组追加到现有JSON文件中

问题描述 投票:0回答:1

每当我运行python脚本时,我都希望为“ O_data”追加数组对象。目前,我正在对值进行硬编码。

我正在尝试以下代码并使用JSON:到目前为止,手动传递值,然后值将通过参数传递。每当我运行此脚本时,仅应将gap1,gap2,gap3和gap4添加到新数组中。登录名和管道名称将相同,我将永远不会改变。因此,请帮助您。


logid = 100
pipename = "abc"
gap1 = 0.25
gap2 = 0.44
gap3 = 0.65
gap4 = 0.56
TA= "TA"

def write_json(data, filename='out1234.json'):
    with open(filename, 'a') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


var1 = {'Gap1': gap1, 'Gap2': gap2, 'Gap3': gap3, 'Gap4': gap4}

result1 = {"logid": logid,
                   "pipename": pipename,
                   "TA": TA,
                    "O_data":[var1],}

write_json(result1)

如果我两次运行文件,将会得到以下结果:

{
  "logid": 100,
  "pipename": "abc",
  "TA": "TA",
  "O_data": [
    {
      "Gap1": 0.25,
      "Gap2": 0.44,
      "Gap3": 0.65,
      "Gap4": 0.56
    }
  ]
}{
  "logid": 100,
  "pipename": "abc",
  "TA": "TA",
  "O_data": [
    {
      "Gap1": 0.25,
      "Gap2": 0.44,
      "Gap3": 0.65,
      "Gap4": 0.56
    }
  ]
}

但是我想要类似JSON格式的结果:

{
  "logid": 100,
  "pipename": "abc",
  "TA": "TA",
  "O_data": [
    {
      "Gap1": 0.25,
      "Gap2": 0.44,
      "Gap3": 0.65,
      "Gap4": 0.56
    },
    {
      "Gap1": 0.25,
      "Gap2": 0.44,
      "Gap3": 0.65,
      "Gap4": 0.56
    }
  ]
}

感谢您的帮助。预先感谢。

python json pycharm
1个回答
0
投票

[您将在现有的JSON上追加新的JSON(如文本,可以从} {之间缺少逗号看出来)。这与向“ O_data”字段添加值不同。

import json

def read_json(filename):
    with open(filename, 'r') as f:
        return json.load(f)

def write_json(filename, data):
    with open(filename, 'w') as f:
        json.dump(data, f)

data = read_json('file.json')
data['O_data'].append(stuff)

write_json('file.json', data)
© www.soinside.com 2019 - 2024. All rights reserved.