Added 2 functions to store dataclasses in json files.
This commit is contained in:
parent
57463e8ebb
commit
9bb90c14f1
1 changed files with 16 additions and 1 deletions
17
data_file.py
17
data_file.py
|
@ -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()
|
||||||
|
|
Loading…
Reference in a new issue