Friday, June 3, 2022

[SOLVED] How to fill dynamically a json file

Issue

im using this block of code to send some data from a Pi to the cloud (needs to be in a json format). However i would also like to save the data in a created json file. Everything concerning the sending to the cloud works as i can send the values one by one but in the json file i have some problems. As anyone can see with my commands:

with open('json_body.json', 'w') as json_file:
           json.dump(data, json_file)

i create a json file but only the latest "data" value is being saved. Does anyone know how can i save all of them ? do i have to use an array or a list to save them first? Any suggestions are helpful. Thank you in advance!

while True:
       acc = ReadChannel(acc_channel)
     # Print out results
       print("--------------------------------------------")
       print("Acc : " , acc , ",Acc in volts", ConvertVolts(acc,2))
       data = {}
       data['acceleration'] = acc
       json_body = json.dumps(data)
       print("Sending message: ", json_body)
       counter = counter + 1
       print(counter)
       with open('json_body.json', 'w') as json_file:
           json.dump(data, json_file)
       await device_client.send_message(json_body)
     # Wait before repeating loop
       time.sleep(delay)
   await device_client.disconnect()

Solution

There is no need to do file write operation in every iteration you can try writing all data at once after the loop end.


temporary_json = []
    
while True:
    acc = ReadChannel(acc_channel)
    # Print out results
    print("--------------------------------------------")
    print("Acc : ", acc, ",Acc in volts", ConvertVolts(acc, 2))
    data = {}
    data["acceleration"] = acc
    json_body = json.dumps(data)
    print("Sending message: ", json_body)
    counter = counter + 1
    print(counter)
    temporary_json.append(json.dumps(data))
    await device_client.send_message(json_body)
    # Wait before repeating loop
    time.sleep(delay)
    
with open("json_body.json", "w") as json_file:
    proper_json = ",".join(temporary_json)  # making a valid json out of temporary json
    json.dump(proper_json, json_file)

awaitdevice_client.disconnect()


Answered By - Vishal Singh
Answer Checked By - Terry (WPSolving Volunteer)