0

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.

1
  • @VishatJ why you need to run this 2 or more times? Commented Feb 6, 2020 at 8:48

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for swift response. It working absolutely fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.