Python Forum

Full Version: Writing to json file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
At times, the below function writes an extra "}" in the json file and I cannot see where the problem may lie. I appreciate some guidance.
Micropython running on Raspberry Pico W
TIA

# write to file
def w_json(key, txt):
    try:
        with open(json_file, 'r+') as f:
            data = json.load(f)
#             print("data", data)
            data[key] = txt
            f.seek(0) # set pointer to first line
            print("json_data", data)
            json.dump(data, f)
    except Exception as e: 
        print(e)
        pass
Output:
{"set_soil1": "2.67", "soil1": 0.4, "soil2": 0.35, "set_soil2": "4.77"}}
I don't think an extra "}" is written to the file. I think it is already there. You should use truncate() instead of seek().