I am trying to save my objects created, stored in the __objects class attribute, and I am getting error:
Traceback (most recent call last):
File "/home/leuel/PycharmProjects/AirBnB_clone/./test_save_reload_base_model.py", line 2, in <module>
from models import storage
File "/home/leuel/PycharmProjects/AirBnB_clone/models/__init__.py", line 4, in <module>
storage.reload()
File "/home/leuel/PycharmProjects/AirBnB_clone/models/engine/file_storage.py", line 32, in reload
self.__objects = json.load(f)
File "/usr/lib/python3.10/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.10/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)
The method that I used to save to the json file:
def save(self):
with open(self.__file_path, "w+") as f:
json.dump(self.__objects, f)
The __objects attribute is a class attribute that is a dictionary holding all instances (instances will be stored using a key based on their ids). Why am I getting the error? Initially, the __objects will be an empty dictionary
And another question when referencing class attributes, should I use self or should I write the class name? If I should write the class name, is it because instances might change the class attribute? I am new to python and JSON, so excuse me if my question is not clear enough.
EDIT: As @Richard Neumann, pointed out, my error comes from json.load(). Here is the code where I called the json.load():
def reload(self):
if path.isfile(self.__file_path):
with open(self.__file_path, "r", encoding="utf-8") as f:
self.__objects = json.load(f)
The reload method will reload the __objects class attribute from a file.json file. I did this to recreate instances when I reopen my program
json.dumptwice in yoursave()method? Did you mean:json.dump(self.__objects, f)?selfinside the class methods. If they are public and you are calling them outside the class,then use the name of the instance.json.dump(self.__objects, f)still gives me the same errorjson.load(), not onjson.dump(). Show us the actual code where the error occurs, i.e. where you invokejson.load()as well as the contents of the respective file.dict. ie{}