Skip to content

Instantly share code, notes, and snippets.

@danielrw7
Last active August 26, 2016 04:31
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 danielrw7/53f371acc7165bcd4f5d17de0116630f to your computer and use it in GitHub Desktop.
Save danielrw7/53f371acc7165bcd4f5d17de0116630f to your computer and use it in GitHub Desktop.
import json, os.path
def json_load(filepath):
return json.load(open(filepath))
def valid_filenames(filenames):
return map(os.path.realpath, filter(os.path.exists, filenames))
def merge(*dicts):
res = {}
for value in dicts:
if isinstance(value, dict):
res.update(value)
return res
class JSONConfig:
def __init__(self, filenames=[], allowDotNotation=False):
self.filenames = filenames
self.allowDotNotation = allowDotNotation
self.reload()
def set_config_list(self):
self.config_list = []
for filename in self.valid_filenames:
try:
self.config_list.append(self.file_contents[filename])
except:
pass
def set_config_merged(self):
self.config = merge(*self.config_list)
def load_files(self, filenames=[]):
map(self.load_file, filenames)
def load_file(self, filename):
try:
self.file_contents[filename] = json_load(filename)
except:
pass
def reload(self):
self.valid_filenames = valid_filenames(self.filenames)
self.file_contents = {}
self.load_files(self.valid_filenames)
self.set_config_list()
self.set_config_merged()
def get(self, key):
if not isinstance(key, str):
raise TypeError("Invalid parameter type for `key`")
try:
value = self.config
if self.allowDotNotation:
for part in key.split("."):
value = value[part]
else:
value = value[key]
return value
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment