Home > Back-end >  Json file cant be edited
Json file cant be edited

Time:09-29

I want to append the brightness 0 to all lamps in list to a empty json file.

def first_start(lamps:list):
for lamp in lamps:
    dict = {"light": {lamp: {"brightness": 0}}}
    with open("data.json", "r") as file:
        data = json.load(file)
        data.update(dict)
    print(dict)
    with open("data.json", 'w') as file:
        json.dump(data, file)

Everytime I run this code, I get this error:

Traceback (most recent call last):
  File "C:\Users\brend\PycharmProjects\Hue_Control\main.py", line 27, in <module>
    first_start(lamps)
  File "C:\Users\brend\PycharmProjects\Hue_Control\main.py", line 16, in first_start
    data = json.load(file)
  File "C:\Users\brend\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\brend\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\brend\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\brend\AppData\Local\Programs\Python\Python39\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)

Could somebody please help me, what im doing wrong? Thank you :)

CodePudding user response:

There is no such thing as an empty json file. If you have an empty file, then its not a json file.

You could ignore all the errors and assume that the file should contain "{}" and carry on:

def first_start(lamps:list):
    for lamp in lamps:
        upd = {"light": {lamp: {"brightness": 0}}}
        data = {}  # Empty dict just in case

        try:
            with open("data.json", "r") as file:
                data = json.load(file)
        except Exception:
            print('Ignore errors with data.json')
        data.update(upd)

        with open("data.json", 'w') as file:
            json.dump(data, file)
  • Related