Last active
November 12, 2019 17:35
-
-
Save Niedzwiedzw/efdebfcd2373edd275d4027b3ad998c2 to your computer and use it in GitHub Desktop.
A quick way to have your class be serializable to json in a nested way
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 dumps | |
from copy import deepcopy | |
class JsonSerializable: | |
@staticmethod | |
def _to_json(item): | |
if isinstance(item, JsonSerializable): | |
return item.json | |
if isinstance(item, list): | |
return list(map(JsonSerializable._to_json, item)) | |
if isinstance(item, dict): | |
return {k: JsonSerializable._to_json(v) for k, v in item.items()} | |
return item | |
@property | |
def json(self): | |
return dumps({k: JsonSerializable._to_json(v) for k, v in self.__dict__.items()}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment