From 9bb90c14f1f12dfff9696ef68da63dbc839a324f Mon Sep 17 00:00:00 2001 From: EKNr1 Date: Sun, 25 Feb 2024 14:29:14 +0100 Subject: [PATCH] Added 2 functions to store dataclasses in json files. --- data_file.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/data_file.py b/data_file.py index 29143c0..8280726 100644 --- a/data_file.py +++ b/data_file.py @@ -1,7 +1,6 @@ #!/usr/bin/python3 import json -from dataclasses import dataclass class DictFile: @@ -99,3 +98,19 @@ class DataclassJSONFile: def __len__(self): 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()