Skip to content

Instantly share code, notes, and snippets.

@pydanny
Created January 17, 2024 17:53
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 pydanny/56c4c26a4b9f8f0c16575105781c85b6 to your computer and use it in GitHub Desktop.
Save pydanny/56c4c26a4b9f8f0c16575105781c85b6 to your computer and use it in GitHub Desktop.
import pydantic
def to_json(cls):
cls.to_json = lambda self: pydantic.RootModel[cls](self).model_dump_json()
return cls
@to_json
@pydantic.dataclasses.dataclass
class A:
a: int
b: str
def to_json(self):
return pydantic.RootModel[self.__class__](self).model_dump_json()
a = A(1, 'a')
a.to_json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment