Last active
December 17, 2024 02:57
-
-
Save TerribleDev/a7bff984dd8f694330a04b8190cf1b62 to your computer and use it in GitHub Desktop.
Super Enhanced Json encoder
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
import dataclasses | |
import datetime | |
import decimal | |
import json | |
import uuid | |
# example | |
# json.dumps({ }, cls=SuperEnhancedJSONEncoder) | |
class SuperEnhancedJSONEncoder(json.JSONEncoder): | |
def default(self, o): | |
if dataclasses.is_dataclass(o): | |
return dataclasses.asdict(o) | |
if isinstance(o, datetime.datetime): | |
r = o.isoformat() | |
if o.microsecond: | |
r = r[:23] + r[26:] | |
if r.endswith("+00:00"): | |
r = r[:-6] + "Z" | |
return r | |
elif isinstance(o, datetime.date): | |
return o.isoformat() | |
elif isinstance(o, datetime.time): | |
if is_aware(o): | |
raise ValueError("JSON can't represent timezone-aware times.") | |
r = o.isoformat() | |
if o.microsecond: | |
r = r[:12] | |
return r | |
elif isinstance(o, datetime.timedelta): | |
return duration_iso_string(o) | |
elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): | |
return str(o) | |
elif hasattr(o, 'to_json') is False: | |
return o.__dict__ | |
else: | |
return super().default(o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment