Skip to content

Instantly share code, notes, and snippets.

@michaeltrainor
Created August 24, 2017 12:03
Show Gist options
  • Save michaeltrainor/de03b09cb9368783782331f552d1e926 to your computer and use it in GitHub Desktop.
Save michaeltrainor/de03b09cb9368783782331f552d1e926 to your computer and use it in GitHub Desktop.
# standard libraries
import os
import sys
import json
import traceback
class JSONDict(dict):
def __init__(self, file_path, sort_keys=False, *args, **kwargs):
super(JSONDict, self).__init__(*args, **kwargs)
self.file_path_ = file_path
self.sort_keys_ = sort_keys
if os.path.exists(file_path):
try:
with open(self.file_path_) as raw:
data = json.load(raw)
self.update(data)
except (WindowsError, IOError) as error_:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
del exc_info
else:
try:
open(self.file_path_, "w+")
except (WindowsError, IOError) as error_:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
del exc_info
def __getattr__(self, item):
return self.get(item)
def __setitem__(self, key, value):
super(JSONDict, self).__setitem__(key, value)
self.__update_json__()
def __delitem__(self, key):
super(JSONDict, self).__delitem__(key)
self.__update_json__()
def clear(self):
super(JSONDict, self).clear()
self.__update_json__()
def update(self, other, **kwargs):
super(JSONDict, self).update(other)
self.__update_json__()
def __update_json__(self):
try:
if os.access(self.file_path_, os.W_OK):
with open(self.file_path_, "w") as file_path_:
json.dump(self, file_path_, sort_keys=self.sort_keys_, indent=2)
else:
return
except (WindowsError, IOError) as error_:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
del exc_info
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment