diff options
Diffstat (limited to 'morphlib/morph2.py')
-rw-r--r-- | morphlib/morph2.py | 37 |
1 files changed, 22 insertions, 15 deletions
diff --git a/morphlib/morph2.py b/morphlib/morph2.py index 4fdf7ba4..edf7bb31 100644 --- a/morphlib/morph2.py +++ b/morphlib/morph2.py @@ -17,16 +17,8 @@ import copy import re -# It is intentional that if collections does not have OrderedDict that -# simplejson is also used in preference to json, as OrderedDict became -# a member of collections in the same release json got its object_pairs_hook -try: # pragma: no cover - from collections import OrderedDict - import json -except ImportError: # pragma: no cover - from ordereddict import OrderedDict - import simplejson as json - +import morphlib +from morphlib.util import OrderedDict, json class Morphology(object): @@ -61,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() @@ -165,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) |