diff options
author | Richard Maw <richard.maw@codethink.co.uk> | 2013-01-18 16:18:20 +0000 |
---|---|---|
committer | Javier Jardón <javier.jardon@codethink.co.uk> | 2013-01-22 18:34:22 +0000 |
commit | 7ef9cb8922bd933ae8ee58cb24a2b38844a0e629 (patch) | |
tree | 74f71465c0002d98b8c741f4d728dc3cf6f620ad /morphlib/morph2.py | |
parent | a8d30277932099dcae31f99d3fbd531f74eb0249 (diff) | |
download | morph-7ef9cb8922bd933ae8ee58cb24a2b38844a0e629.tar.gz |
Parse as YAML if not valid JSON
Tests are currently broken, one because invalid JSON
can be valid YAML, and coverage is incomplete.
Diffstat (limited to 'morphlib/morph2.py')
-rw-r--r-- | morphlib/morph2.py | 26 |
1 files changed, 21 insertions, 5 deletions
diff --git a/morphlib/morph2.py b/morphlib/morph2.py index 9e5be2e6..edf7bb31 100644 --- a/morphlib/morph2.py +++ b/morphlib/morph2.py @@ -17,6 +17,7 @@ import copy import re +import morphlib from morphlib.util import OrderedDict, json class Morphology(object): @@ -52,8 +53,26 @@ class Morphology(object): ] } + @staticmethod + def _load_json(text): + return json.loads(text, object_pairs_hook=OrderedDict) + + @staticmethod + def _dump_json(obj, f): + text = json.dumps(obj, indent=4) + text = re.sub(" \n", "\n", text) + f.write(text) + f.write('\n') + def __init__(self, text): - self._dict = json.loads(text, object_pairs_hook=OrderedDict) + # Load as JSON first, then try YAML, so morphologies + # that read as JSON are dumped as JSON, likewise with YAML. + try: + self._dict = self._load_json(text) + self._dumper = self._dump_json + except Exception, e: + self._dict = morphlib.yamlparse.load(text) + self._dumper = morphlib.yamlparse.dump self._set_defaults() self._validate_children() @@ -156,7 +175,4 @@ class Morphology(object): value = self[key] if value and key[0] != '_': as_dict[key] = value - text = json.dumps(as_dict, indent=4) - text = re.sub(" \n", "\n", text) - f.write(text) - f.write('\n') + self._dumper(as_dict, f) |