Skip to content

Instantly share code, notes, and snippets.

@deeuu
Last active May 29, 2019 16:50
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 deeuu/b2252a55a20da7182423e5633acaefc0 to your computer and use it in GitHub Desktop.
Save deeuu/b2252a55a20da7182423e5633acaefc0 to your computer and use it in GitHub Desktop.
JSON for quick config file
class JSONConfigParser():
import collections
Option = collections.namedtuple('Option', 'type is_required default')
def __init__(self):
self._expected = {}
def add_option(self, option, type, is_required=False, default=None):
self._expected[option] = self.Option(type, is_required, default)
def parse(self, file):
with open(file, 'r') as f:
config = json.load(f)
out = {}
for k, v in self._expected.items():
if k in config:
v2 = config[k]
if isinstance(v2, v.type):
out[k] = v2
else:
raise TypeError(f"Option {k} should be of type {v.type}")
elif v.is_required:
raise ValueError(
f'JSON is missing option {k} of type {v.type}'
)
else:
out[k] = v.default
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment