Last active
August 8, 2021 13:41
-
-
Save techiev2/cc40745f4d217797bb425ca94b4a30d6 to your computer and use it in GitHub Desktop.
Recursively convert a JSON structure to an object
This file contains 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 json import loads | |
from dataclasses import dataclass | |
@dataclass | |
class BaseObject: | |
@classmethod | |
def from_dict(cls, _dict): | |
entity = BaseObject() | |
entity.__dict__ = _dict | |
return entity | |
@classmethod | |
def from_string(cls, string): | |
entity = BaseObject() | |
_dict = loads(string) | |
for key, value in _dict.items(): | |
_cls = globals().get(key) | |
if _cls and hasattr(_cls, "from_dict"): | |
_dict[key] = _cls.from_dict(value) | |
entity.__dict__ = _dict | |
return entity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment