Last active
September 6, 2022 20:56
-
-
Save luhn/238669a4940876e6c38a288dc2609c57 to your computer and use it in GitHub Desktop.
Override default JSON encoder to add support for dataclasses
This file contains hidden or 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 json | |
from dataclasses import dataclass, is_dataclass, asdict | |
class DataclassEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if is_dataclass(obj): | |
return asdict(obj) | |
return super().default(obj) | |
@dataclass | |
class MyData: | |
foo: int | |
# Monkeypatch the stdlib | |
# This is extremely bad practice and may break your application in unexpected | |
# ways. Use at your own risk. | |
json._default_encoder = DataclassEncoder( | |
skipkeys=False, | |
ensure_ascii=True, | |
check_circular=True, | |
allow_nan=True, | |
indent=None, | |
separators=None, | |
default=None, | |
) | |
print(json.dumps(MyData(foo=1))) | |
# Output: {"foo": 1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment