Pydantic: How to export dataclass?

Created on 14 May 2020  路  6Comments  路  Source: samuelcolvin/pydantic

How to export dataclass?

             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.

question

Most helpful comment

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}

All 6 comments

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.

Was this page helpful?
0 / 5 - 0 ratings