Last active
March 29, 2022 17:19
-
-
Save dario61081/a3a32f10a186b79b278905202005fcfd to your computer and use it in GitHub Desktop.
Class JsonEncode override for custom date format v1.0.1
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
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