Skip to content

Instantly share code, notes, and snippets.

@linw1995
Created April 14, 2021 06:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linw1995/fcddcd57e5c18f8f37b8853fb6a6eb36 to your computer and use it in GitHub Desktop.
Save linw1995/fcddcd57e5c18f8f37b8853fb6a6eb36 to your computer and use it in GitHub Desktop.
How to add custom convertors for JSON serializer in Python
import dataclasses
import json
from datetime import datetime
def convertor(v):
if isinstance(v, datetime):
return v.timestamp()
elif dataclasses.is_dataclass(v):
return dataclasses.asdict(v)
type_name = v.__class__.__name__
raise TypeError(f"Object of type {type_name!r} is not JSON serializable")
@dataclasses.dataclass
class Bar:
created_at: datetime = dataclasses.field(default_factory=datetime.now)
print(json.dumps(Bar(), default=convertor))
# {"created_at": 1618383433.054921}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment