Skip to content

Instantly share code, notes, and snippets.

@entirelymagic
Last active October 22, 2021 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save entirelymagic/d3b45d07eaa0a9a745484c76ef401720 to your computer and use it in GitHub Desktop.
Save entirelymagic/d3b45d07eaa0a9a745484c76ef401720 to your computer and use it in GitHub Desktop.
JsonFileHandler/Serializer/Deserializer
import json
import os
class JsonFileHandler:
"""Given the name of the json file location, data can be extracted or added.
If the location does not exists it will be created.
"""
def __init__(self, file_name: str) -> None:
self.file = file_name
def check_if_folder_or_file_exists(self) -> None:
if not os.path.isfile(self.file):
with open(self.file, 'w') as f:
json.dump({}, f)
# if a folder from the file name does not exist, create it
def create_folder_and_file(self) -> None:
if not os.path.exists(os.path.dirname(self.file)):
os.makedirs(os.path.dirname(self.file))
with open(self.file, "w") as f:
json.dump({}, f)
def deserialize(self) -> dict:
self.check_if_folder_or_file_exists()
with open(self.file) as f:
content = json.load(f)
return content
def serialize(self, data:any) -> None:
with open(self.file, "w") as f:
json.dump(data, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment