diff --git a/prjxray/xjson.py b/prjxray/xjson.py index c45d7911..a512dc99 100644 --- a/prjxray/xjson.py +++ b/prjxray/xjson.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 -import re +import io import json +import re import sys @@ -48,9 +49,16 @@ def sort(data): def pprint(f, data): + detach = False + if not isinstance(f, io.TextIOBase): + detach = True + f = io.TextIOWrapper(f) sort(data) - json.dump(d, f, sort_keys=True, indent=4) + json.dump(data, f, sort_keys=True, indent=4) f.write('\n') + f.flush() + if detach: + f.detach() if __name__ == "__main__": diff --git a/prjxray/xyaml.py b/prjxray/xyaml.py index 40e3bc2f..a7a8754d 100644 --- a/prjxray/xyaml.py +++ b/prjxray/xyaml.py @@ -5,9 +5,13 @@ import yaml import json import unittest +from prjxray import xjson + def load(f): data = f.read() + if isinstance(data, bytes): + data = data.decode('utf-8') # Strip out of ! data = re.sub("!<[^>]*>", "", data) return yaml.load(io.StringIO(data)) @@ -15,7 +19,9 @@ def load(f): def tojson(f): d = load(f) - return json.dumps(d, sort_keys=True, indent=4) + o = io.StringIO() + xjson.pprint(o, d) + return o.getvalue() class XYamlTest(unittest.TestCase):