Json.load rising "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" even with an "anti_empty" condition

Viewed 41

I already post about my problem and I thought it was solved, but after a few time the error rise again. I'm gonna explain my program from the beginning. I got a Json file that contain values permanently update by another program, I want to get an overlay that display those values, that means I got to open and read my json file every second (or more) with the "after()" method. (Im using tkinter for my overlay). When I run my tkinter window without the other program that update the values, everything work perfectly, I can update manually a value and it will be update on the overlay. When I run both programs together after an amount of time, I get the empty json error, sometimes after 5 minutes, sometimes after 45 minutes, It's random. I tried the following issues : Issue 1 :

def is_json(): 
    with open ('my_json') as my_file :
        myjson = my_file.read()
    try: 
        json_object = json.loads(myjson) 
    
    except json.JSONDecodeError as e: 
        return False 
    return True
if is_json():
     with open ('my_json') as my_file:
         data = json.load(my_file)
else : 
     time.sleep(0.1)

Issue 2:

 while True:
     if os.path.getsize("/my_json") > 0:
        with open ('my_json') as my_file :
            myjson = my_file.read()
     else:
        time.sleep(0.2)

I tryed another one, but I dont want to code it again, that was a function that allow one program to read/write on the json only in "even" seconds and the other one can only do it in "odd" second. I try this to avoid interactions, cause I think that's my problem, but none of those solutions worked.

1 Answers

You should return the parsed JSON in the same function that has the try/except. Otherwise, the file could change between calling is_json() and json.load().

def json_load_retry(filename, sleeptime=0.1):
    while True:
        with open(filename) as f:
            try:
                return json.load(f)
            except json.JSONDecodeError:
                time.sleep(sleeptime)

myjson = json_load_retry('my_json', sleeptime=0.2)
Related