aboutsummaryrefslogtreecommitdiff
path: root/netclass/jsonconverter.py
diff options
context:
space:
mode:
authorDeclan Hoare <[email protected]>2020-04-16 22:58:21 +1000
committerDeclan Hoare <[email protected]>2020-04-16 23:10:44 +1000
commit7000fce72fbec34c6f4957a59d4146cc7148ee59 (patch)
tree5affe93d68a7fbcc6cf85a4d9a3eedecc730d1f7 /netclass/jsonconverter.py
downloadshiftgears-7000fce72fbec34c6f4957a59d4146cc7148ee59.tar.gz
shiftgears-7000fce72fbec34c6f4957a59d4146cc7148ee59.tar.bz2
shiftgears-7000fce72fbec34c6f4957a59d4146cc7148ee59.zip
Initial Release
Diffstat (limited to 'netclass/jsonconverter.py')
-rw-r--r--netclass/jsonconverter.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/netclass/jsonconverter.py b/netclass/jsonconverter.py
new file mode 100644
index 0000000..8029fcd
--- /dev/null
+++ b/netclass/jsonconverter.py
@@ -0,0 +1,26 @@
+
+import decimal
+import json
+
+from .netclass import netclass_root
+
+class _encoder(json.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, netclass_root):
+ return obj._contents
+ elif isinstance(obj, decimal.Decimal):
+ return float(obj)
+ else:
+ return super().default(obj)
+
+def from_json(t, j):
+ print(repr(j))
+ val = json.loads(j)
+ if issubclass(t, netclass_root):
+ val = t.from_dict(val)
+ if not isinstance(val, t):
+ raise ValueError(f"the JSON value was of type {type(val)}, not {t}")
+ return val
+
+def to_json(obj):
+ return json.dumps(obj, cls=_encoder)