Home > Blockchain >  How to append value inside list in json?
How to append value inside list in json?

Time:01-27

I am trying to append value inside the list,but whenever I re run the server it overwrites the value. How can I effectively write in the json file.

{ "heart_rate": [ 72.18 ], "Experiment_time": [ 01/22/2023 11:59:59 ] }

I want to add values in json file, When ever I get new value it should get append inside the heartrate and Experiment_time list inside the corresponding keys, similar to below mentioned format.

{ "heart_rate": [ 72.18,73.44 ], "Experiment_time": [ 01/22/2023 11:59:59,01/22/2023 11:60:00 ] }

What I am tring is to first read the json file if it exists, If it doesn't create one.

try:
    with open('Accounts.json','r') as fp:
        data = json.load(fp)
        f = data
        print(f)
        heartrate,dt_string = perform_all()

        lst1 = []

        if f != '':
            print("something")
        else:
            lst1.append(heartrate)
            
except :
    print("File Not found. Creating One")
    
    data = {}
    data['heart_rate'] = [None]
    data['Experiment_time'] = [None]
    
    
with open('Accounts.json','w') as fp:
    json.dump(data,fp,indent = 4)
heartrate,dt_string = perform_all() 

is a function that returns 1 value of heartrate and 1 value of datetime when called

CodePudding user response:

Close, just append to the right dictionary key. Note that JSON should be encoded in UTF-8 and not all OSes default to that encoding. It will matter if you write non-ASCII characters. Also bare except is a bad practice. Put the exception you expect.

import json
import datetime as dt

def perform_all():
    return 85, dt.datetime.now().strftime('%m/%d/%y %H:%M:%S')

try:
    with open('Accounts.json', encoding='utf8') as fp:
        data = json.load(fp)
        heartrate, dt_string = perform_all()
        data['heart_rate'].append(heartrate)
        data['Experiment_time'].append(dt_string)
except FileNotFoundError:
    print('File not found.  Creating initial data...')
    data = {'heart_rate': [], 'Experiment_time': []}
       
with open('Accounts.json', 'w', encoding='utf8') as fp:
    json.dump(data, fp, indent=2)

Output:

C:\>test
File not found.  Creating one...

C:\>test

C:\>test

C:\>type Accounts.json
{
  "heart_rate": [
    85,
    85
  ],
  "Experiment_time": [
    "01/26/23 21:34:22",
    "01/26/23 21:34:23"
  ]
}
  • Related