Skip to content

Instantly share code, notes, and snippets.

@luhn
Last active September 6, 2022 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luhn/238669a4940876e6c38a288dc2609c57 to your computer and use it in GitHub Desktop.
Save luhn/238669a4940876e6c38a288dc2609c57 to your computer and use it in GitHub Desktop.
Override default JSON encoder to add support for dataclasses
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