Skip to content

Instantly share code, notes, and snippets.

@GiullianoRossi1987
Created December 14, 2019 14:06
Show Gist options
  • Save GiullianoRossi1987/512afd7bf96a5db65b85d7d8b44819ad to your computer and use it in GitHub Desktop.
Save GiullianoRossi1987/512afd7bf96a5db65b85d7d8b44819ad to your computer and use it in GitHub Desktop.
A generic class for manage JSON files with python.
# coding = utf-8
# using namespace std
import json
from typing import AnyStr
class JSONConnection(object):
"""
"""
json_file = AnyStr
got_json = False
document = dict()
class InvalidFileExt(Exception):
""" If the selected file is not a JSON file. """
class DatabaseAlreadyLoaded(Exception):
""" If the database already haves a JSON file connected """
class DatabaseNotLoaded(Exception):
""" If the class don't have a JSON file connected """
@staticmethod
def check_file_ext(file_nm: AnyStr) -> bool:
"""
"""
return str(file_nm).split(".")[-1] == "json"
def connect_file(self, file_json: AnyStr):
"""
"""
if self.got_json: raise self.DatabaseAlreadyLoaded("The class already have a JSON loaded")
if not self.check_file_ext(file_json): raise self.InvalidFileExt(f"The file {file_json} is not a JSON file")
with open(file_json, "r") as json_to:
self.document = json.loads(json_to.read())
self.json_file = file_json
self.got_json = True
def disconnect_file(self):
"""
"""
if not self.got_json: raise self.DatabaseNotLoaded("There's no connection already")
self.json_file = AnyStr
self.document = dict()
self.got_json = False
def commit_changes(self):
"""
"""
if not self.got_json: raise self.DatabaseNotLoaded("There's no connection with a file")
dumped = json.dumps(self.document)
with open(self.json_file, "w+") as json_file: json_file.write(dumped)
del dumped
def get_doc(self) -> dict:
"""
"""
return self.document
def get_json(self) -> AnyStr:
"""
"""
return self.json_file
def get_json_name(self) -> str:
"""
"""
return str(self.json_file)
def get_got_connection(self) -> bool:
"""
"""
return self.got_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment