Skip to content

Instantly share code, notes, and snippets.

@dario61081
Last active March 29, 2022 17:19
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 dario61081/a3a32f10a186b79b278905202005fcfd to your computer and use it in GitHub Desktop.
Save dario61081/a3a32f10a186b79b278905202005fcfd to your computer and use it in GitHub Desktop.
Class JsonEncode override for custom date format v1.0.1
class BetterJsonEncode(JSONEncoder):
def default(self, obj):
if isinstance(obj, date):
return obj.isoformat()
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, decimal.Decimal):
return float(obj)
if hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):
return dict(obj)
if hasattr(obj, '__dict__'):
return {member: getattr(obj, member)
for member in dir(obj)
if not member.startswith('_') and
not hasattr(getattr(obj, member), '__call__')}
return json.JSONEncoder.default(self, obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment