Skip to content

Instantly share code, notes, and snippets.

@techiev2
Last active August 8, 2021 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techiev2/cc40745f4d217797bb425ca94b4a30d6 to your computer and use it in GitHub Desktop.
Save techiev2/cc40745f4d217797bb425ca94b4a30d6 to your computer and use it in GitHub Desktop.
Recursively convert a JSON structure to an object
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