简体   繁体   中英

Append the array of object into existing JSON file through Python script

I want to append object of array for "O_data" whenever I run python script. For the time being I am hard coding the value.

I am trying the following code and imoprting JSON:
Passing the values manually as of now and the value will come through argument. Whenever I will run my this script then only gap1 gap2 gap3 and gap4 should added to new array. logid and pipename will same, I will never change. So please help you can.


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)

and I am getting the following result if I run file twice:

{
  "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
    }
  ]
}

But I want the result in JSON format like:

{
  "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
    }
  ]
}

Any help is appreciated. Thanks in advance.

You are appending a new JSON on the pre-existing (as text, as can be seen by the lack of a comma between }{). This is not the same as adding a value to the 'O_data' field.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM