Added 2 functions to store dataclasses in json files.

This commit is contained in:
The Wobbler 2024-02-25 14:29:14 +01:00
parent 57463e8ebb
commit 9bb90c14f1

View file

@ -1,7 +1,6 @@
#!/usr/bin/python3 #!/usr/bin/python3
import json import json
from dataclasses import dataclass
class DictFile: class DictFile:
@ -99,3 +98,19 @@ class DataclassJSONFile:
def __len__(self): def __len__(self):
return len(self.class_instance.__dict__) return len(self.class_instance.__dict__)
def load_dataclass_json(dataclass, file_path: str):
file = open(file_path, "r")
class_dict = json.load(file)
file.close()
return dataclass(**class_dict)
def save_dataclass_json(class_instance, file_path: str):
class_dict = class_instance.__dict__
file = open(file_path, "w")
json.dump(class_dict, file)
file.close()