Created
June 21, 2019 20:29
-
-
Save ollyjshaw/042f10b2462d063720fecf350b92155f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from dacite import from_dict | |
import dataclasses | |
import types | |
import json | |
@dataclass | |
class Bar: | |
age: int | |
@dataclass | |
class Foo: | |
name: str | |
bar: Bar | |
def test_can_convert_from_dict(): | |
input = {'name': "Olly", 'bar': {'age': 12}} | |
foo = Foo(**input) | |
assert foo.name == "Olly" | |
# assert foo.bar.age == 12 # DOES NOT WORK | |
def test_can_convert_to_json(): | |
input = Foo("Olly", Bar(12)) | |
asjson = json.dumps(input, cls=EnhancedJSONEncoder) | |
assert asjson == r'{"name": "Olly", "bar": {"age": 12}}' | |
def test_can_convert_from_json_to_dict(): | |
input = r'{"name": "Olly", "bar": {"age": 12}}' | |
as_dict = json.loads(input) | |
assert as_dict['bar']['age'] == 12 | |
def test_can_convert_from_json_to_dataclass(): | |
input = r'{"name": "Olly", "bar": {"age": 12}}' | |
as_dict = json.loads(input) | |
foo = from_dict(data_class=Foo, data=as_dict) | |
assert foo.bar.age == 12 | |
def test_can_convert_from_dict_to_dataclass(): | |
input = {'name': "Olly", 'bar': {'age': 12}} | |
foo = from_dict(data_class=Foo, data=input) | |
assert foo.bar.age == 12 | |
class EnhancedJSONEncoder(json.JSONEncoder): | |
def default(self, o): | |
if dataclasses.is_dataclass(o): | |
return dataclasses.asdict(o) | |
return super().default(o) | |
def _dict_to_sns(d): | |
return types.SimpleNamespace(**d) | |
def test_simplenamespace(): | |
my_dict = {'foo': 1, 'bar': {'baz': 2}} | |
my_json = """ {"foo":1, "bar": {"baz": 2}} """ | |
out = json.loads(my_json, object_hook=_dict_to_sns) | |
assert 2 == out.bar.baz | |
out2 = types.SimpleNamespace(**my_dict) | |
assert 1 == out2.foo | |
# assert 2 == out2.bar.baz #won't work |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment