Created
April 14, 2021 06:57
-
-
Save linw1995/fcddcd57e5c18f8f37b8853fb6a6eb36 to your computer and use it in GitHub Desktop.
How to add custom convertors for JSON serializer in Python
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 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