0

I'm quite a newbie of Python and tryed to make a program that creates a list of JSON by compiling a form thanks to tk library and write it in a .json file. But I used a bad logic and everytime I re-run the program, it does exactly what I want and write a new JSON, but it delete the old ones that were written on that file.

getdata = []

def submit():

    name = name_var.get()
    img = img_var.get()
    description = description_var.get()
 
    d = { "name": name, "image": img, "description": description}

    getdata.append(d)

    print("This is what's in the list", getdata)
        
    name_var.set("")
    img_var.set("")
    description_var.set("")

    with open("interest.json",'w', encoding='utf-8') as f:
                json.dump(getdata,f,ensure_ascii=False, indent = 2)

The following is a part of a test I've made to try saving the already existing .json file in a python variable to check if it's empty. Not sure if it's right. I also thought that maybe I have to work with two .json files.

    with open("interest.json",'r') as filetoread:
            
        transform_json = json.loads(filetoread)

        if len(transform_json) < 1:
            with open("interest.json",'w', encoding='utf-8') as f:
                json.dump(getdata,f,ensure_ascii=False, indent = 2)
        else:
            # put a condiction to keep writing on the same file if that already exist

I hope I didn't just choose the worst way to do it. Thank you for the help.

Jack
  • 1
  • 1
  • 1
    https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function `"w"` will truncate your file, you need to use `"a"` - `open('file.json', 'a')` – krish Jun 08 '23 at 08:56

2 Answers2

0

You can refer to the answer here:

Difference between modes a, a+, w, w+, and r+ in built-in open function?

"w" will truncate your file, you need to use "a"

open('file.json', 'a')

krish
  • 166
  • 5
  • This is a bad idea as you will be appending a list of jsons after a list of jsons, creating an invalid file format that can't be parsed [{}, {}, {}][{},{},{}] What @Jack needs is to load the old list of json, append to it the new jsons and dump it back, but it seems to be highly inefficient. – Jorge Ruiz Gómez Jun 08 '23 at 09:04
  • Well, I tried the solution suggested from @krish and yes, you're right. But I noticed something: the previous list got read and then got written exactly as I want, maybe if there'd a way to clean the old "print" and re-writing the whole list on the .json could be the right way – Jack Jun 08 '23 at 09:35
  • Actually, trying further, I noticed also that if the .json already exist, it will append new JSON array but the previous won't be read. Basically it starts a new array each time. – Jack Jun 08 '23 at 09:40
0
import json
import os

transform_json = None
getdata = {"test1":"value"}
if os.path.isfile("interest.json"):
    with open("interest.json", 'r') as filetoread:
        try:
            transform_json = json.load(filetoread)
        except Exception:
            pass

if not transform_json:
    with open("interest.json", 'w', encoding='utf-8') as f:
        json.dump(getdata, f, ensure_ascii=False, indent=2)
else:
    combined_data = {**transform_json, **getdata}

    with open("interest.json", 'w', encoding='utf-8') as f:
        json.dump(combined_data, f, ensure_ascii=False, indent=2)

Using somewhat your code, you could do something along this You open your file, and if it exist load the json inside transform_json as dictionnary, otherwise do nothing

Then you check wether transform_json exist (so wether or not the file exist in the first place). If it doesn't exist, create the file and add your value inside, otherwise, if it exist (so transform_json has value inside it), concat transform_json with your getdata, (to create a single dictionnary) and then dump_it inside your json file to overwrite previously existing json

The try except is in case your json file is invalid (empty file or bad json file), then you overwrite it, if that's not the behavior you want (e.g you want to do something if the json is incorrect, do it instead of pass )