Skip to content

Instantly share code, notes, and snippets.

@Niedzwiedzw
Last active November 12, 2019 17:35
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 Niedzwiedzw/efdebfcd2373edd275d4027b3ad998c2 to your computer and use it in GitHub Desktop.
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
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