Skip to content
Snippets Groups Projects
Commit 96da4ee1 authored by James Graham's avatar James Graham
Browse files

Documentation and small changes to parsers/json

parent 8236405d
No related branches found
No related tags found
No related merge requests found
pycgtool.parsers.json module
============================
.. automodule:: pycgtool.parsers.json
:members:
:undoc-members:
:show-inheritance:
...@@ -7,6 +7,7 @@ Submodules ...@@ -7,6 +7,7 @@ Submodules
.. toctree:: .. toctree::
pycgtool.parsers.cfg pycgtool.parsers.cfg
pycgtool.parsers.json
Module contents Module contents
--------------- ---------------
......
...@@ -2,23 +2,34 @@ import json ...@@ -2,23 +2,34 @@ import json
import os import os
class Record(dict): class AttrDict(dict):
def __setattr__(self, key, value): """
self[key] = value Class allowing dictionary entries to be accessed as attributes as well as keys.
"""
def __getattr__(self, item): def __init__(self, *args, **kwargs):
return self[item] super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
class CFG: class CFG:
"""
Class to read data from JSON files. Supports including other files and filtering a single section.
"""
def __init__(self, filename, from_section=None): def __init__(self, filename, from_section=None):
"""
Create a new CFG JSON parser.
:param filename: JSON file to read
:param from_section: Optional section to select from file
"""
with open(filename) as f: with open(filename) as f:
self._json = json.load(f, object_hook=Record) self._json = json.load(f, object_hook=AttrDict)
# Recurse through include lists and add to self._json
while self._json.include: while self._json.include:
include_file = os.path.join(os.path.dirname(filename), self._json.include.pop()) include_file = os.path.join(os.path.dirname(filename), self._json.include.pop())
with open(include_file) as include_file: with open(include_file) as include_file:
include_json = json.load(include_file, object_hook=Record) include_json = json.load(include_file, object_hook=AttrDict)
for curr, incl in zip(self._json.values(), include_json.values()): for curr, incl in zip(self._json.values(), include_json.values()):
try: try:
...@@ -26,10 +37,13 @@ class CFG: ...@@ -26,10 +37,13 @@ class CFG:
except TypeError: except TypeError:
curr.update(incl) curr.update(incl)
self._records = self._json
if from_section is not None: if from_section is not None:
try:
self._records = self._json[from_section] self._records = self._json[from_section]
else: except KeyError as e:
self._records = self._json e.args = ("Section '{0}' not in file '{1}'".format(from_section, filename),)
raise
def __getitem__(self, item): def __getitem__(self, item):
return self._records[item] return self._records[item]
......
...@@ -49,6 +49,10 @@ class TestParsersJson(unittest.TestCase): ...@@ -49,6 +49,10 @@ class TestParsersJson(unittest.TestCase):
self.assertTrue("DOPC" in cfg) self.assertTrue("DOPC" in cfg)
self.assertTrue("GLY" in cfg) self.assertTrue("GLY" in cfg)
def test_missing_section(self):
with self.assertRaises(KeyError):
cfg = CFG("test/data/water.json", "potato")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment