diff options
author | Sam Thursfield <sam.thursfield@codethink.co.uk> | 2013-01-28 16:57:18 +0000 |
---|---|---|
committer | Sam Thursfield <sam.thursfield@codethink.co.uk> | 2013-01-28 16:57:18 +0000 |
commit | e97bd4be721834e24c32838c2ecd5149ef7c7101 (patch) | |
tree | 195e2ecfa8afb38522b81ed030588eed8785017f /morphlib/morph2.py | |
parent | 2024583a303ef1a79709b7ecc9fc2dce22e8ce98 (diff) | |
parent | e6dc394c0f31429b2f54c77b20223651a0ab68ee (diff) | |
download | morph-e97bd4be721834e24c32838c2ecd5149ef7c7101.tar.gz |
Merge branch 'jjardon/yaml-v2'
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) |