Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing to json file
#1
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"}}
Reply
#2
I don't think an extra "}" is written to the file. I think it is already there. You should use truncate() instead of seek().
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Linefeed when writing "f" strings to text file? Winfried 5 858 Nov-04-2025, 11:51 AM
Last Post: buran
  Errors using json file RonR 5 955 Oct-28-2025, 03:00 PM
Last Post: buran
  .xlsm file can't be opened after writing data to one worksheet mhyatt 4 885 Oct-11-2025, 11:25 PM
Last Post: Pedroski55
  Problems writing a large text file in python Vilius 4 2,033 Dec-21-2024, 09:20 AM
Last Post: Pedroski55
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 2,250 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  writing list to csv file problem jacksfrustration 5 4,139 Jul-04-2024, 08:15 PM
Last Post: deanhystad
  encrypt data in json file help jacksfrustration 1 3,568 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  parse json field from csv file lebossejames 4 3,003 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Python Script to convert Json to CSV file chvsnarayana 8 6,402 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 7,587 Apr-06-2023, 11:15 AM
Last Post: AlphaInc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020