Repository: s-knibbs/dataclasses-jsonschema (python)

Issue:
Add to_json and from_json convenience methods
It'd be nice to add `from_json` and `to_json` methods for convenience

Pull request:
Add to_json and from_json convenience methods
Closes #35 

Patch:
diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index b17098d..a139823 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -1,3 +1,4 @@
+import json
 import sys
 import functools
 from _decimal import Decimal
@@ -730,3 +731,10 @@ class JsonSchemaMixin:
             # The types in the 'typing' module lack the __name__ attribute
             match = re.match(r'typing\.([A-Za-z]+)', str(field_type))
             return str(field_type) if match is None else match.group(1)
+
+    @classmethod
+    def from_json(cls: Type[T], data: str, validate: bool = True, **json_kwargs) -> T:
+        return cls.from_dict(json.loads(data, **json_kwargs), validate)
+
+    def to_json(self, omit_none: bool = True, validate: bool = False, **json_kwargs) -> str:
+        return json.dumps(self.to_dict(omit_none, validate), **json_kwargs)


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
index 793e572..51ac7df 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -219,6 +219,41 @@ def test_serialise_deserialise():
     assert data == f.to_dict()
 
 
+def test_from_json_to_json():
+    data = """
+{
+  "a": "2018-06-03T12:00:00+00:00",
+  "b": [
+    {
+      "z": 1.2,
+      "y": 1.5
+    }
+  ],
+  "c": {
+    "Mon": 1,
+    "Tue": 2
+  },
+  "d": "Wednesday",
+  "f": [
+    "xyz",
+    6
+  ],
+  "g": [
+    "abc"
+  ],
+  "e": "testing",
+  "h": {
+    "z": 0.5,
+    "y": 1.0
+  }
+}
+"""
+    f = Foo.from_json(data)
+    assert f.f == ('xyz', 6)
+    assert f.g == ('abc',)
+    assert data.strip() == f.to_json(indent=2)
+
+
 def test_invalid_data():
     with pytest.raises(ValidationError):
         Point.from_dict({'z': 3.14, 'y': 'wrong'})