pydantic version: 1.5.1
pydantic compiled: False
install path: /usr/local/lib/python3.7/site-packages/pydantic
python version: 3.7.2 (default, Mar 27 2019, 08:41:08) [GCC 6.3.0 20170516]
platform: Linux-4.19.76-linuxkit-x86_64-with-debian-9.8
optional deps. installed: []
Is it even possible to export (to json) dataclass based object?
from pydantic.dataclasses import dataclass
@dataclass
class TestClass:
id: int
>>> TestClass(id=1).json()
AttributeError: 'TestClass' object has no attribute 'json'
>>> TestClass(id=1).__pydantic_model__.dict()
TypeError: dict() missing 1 required positional argument: 'self'
I've read back and forth https://pydantic-docs.helpmanual.io/usage/exporting_models/ and https://pydantic-docs.helpmanual.io/usage/dataclasses/ and could not find anything about it.
dataclasses has an asdict() function which should do the trick: https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict
In [1]: from pydantic.dataclasses import dataclass
...:
...: @dataclass
...: class TestClass:
...: id: int
...:
In [2]: from dataclasses import asdict
In [3]: asdict(TestClass(id=1))
Out[3]: {'id': 1}
And to json directly? Why: I assume this more efficient that doing object->dict->json by myself.
the .json() method converts a pydantic model to a dict and then runs json.dumps() on it with some custom encoders (for datetimes and such). You can do the same with a dataclass like:
In [4]: from pydantic.json import pydantic_encoder
In [5]: from json import dumps
In [6]: dumps(asdict(TestClass(id=1)), default=pydantic_encoder)
Out[6]: '{"id": 1}'
@StephenBrown2 I'm looking for something like this as well. It's not the serialization that I'm most interested in, but the automatic jsonschema generation so we can have typed interfaces at the JSON api layer as well. Think of reusing the specs in a pydantic dataclass to leverage a typed API endpoint.
https://pydantic-docs.helpmanual.io/usage/schema/
If you want to do that, you have to do:
from pydantic.schema import schema
schema([TestClass])
@StephenBrown2 is pydantic using standard json library? Why not ultrajson - i thought this one is the fastest.
It is if you don't overwrite it: https://github.com/samuelcolvin/pydantic/blob/52af9162068a06eed5b84176e987a534f6d9126a/pydantic/main.py#L106-L107
as documented here: https://pydantic-docs.helpmanual.io/usage/exporting_models/#custom-json-deserialisation
Most helpful comment
dataclasseshas anasdict()function which should do the trick: https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict