Python Forum

Full Version: empty json file error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wrote this and since it creates an empty file it give me an error.
with open("food.json", "r+") as file:
    food = json.load(file)
Error:
Traceback (most recent call last): File "c:/Users/User/MyStuff/mltipls.py", line 4, in <module> food = json.load(file) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I fixed it with:
with open("food.json", "r+") as file:
    try:
        food = json.load(file)
    except:
        food = {}
        json.dump(food, file)
I know empty except statements aren't advisable but I don't know what exception to use.
I tried:
except None
except json.decoder.JSONDecodeError
except JSONDecodeError
These all get their own errors.
(Jun-17-2020, 09:50 AM)mcmxl22 Wrote: [ -> ]I wrote this and since it creates an empty file it give me an error.
if the file does not exists, it will not create an empty file, but will raise FileNotFoundError.

If the file exists, but is empty or otherwise not valid JSON
import json
with open("food.json", "r+") as file:
    try:
        food = json.load(file)
    except json.decoder.JSONDecodeError:
        print('this is error')