Sujet : Re: Serializing pydantic enums
De : mats (at) *nospam* wichmann.us (Mats Wichmann)
Groupes : comp.lang.pythonDate : 30. May 2024, 00:02:08
Autres entêtes
Message-ID : <mailman.72.1717023734.2909.python-list@python.org>
References : 1 2 3 4
User-Agent : Mozilla Thunderbird
On 5/29/24 13:27, Larry Martell via Python-list wrote:
On Tue, May 28, 2024 at 11:46 AM Left Right via Python-list
<python-list@python.org> wrote:
>
Most Python objects aren't serializable into JSON. Pydantic isn't
special in this sense.
>
What can you do about this? -- Well, if this is a one-of situation,
then, maybe just do it by hand?
>
If this is a recurring problem: json.dumps() takes a cls argument that
will be used to do the serialization. Extend json.JSONEncoder and
implement the encode() method for the encoder class you are passing. I
believe that the official docs have some information about this too.
Yeah, I know I can do this, but I seem to recall reading that pydantic
handled serialization. Guess not.
Pydantic devotes some of its documentation to serialization.
https://docs.pydantic.dev/latest/concepts/serialization/As noted elsewhere, some Python objects are easy to serialize, some you need to provide some help. Consider pickling: if you write a class that isn't obviously pickleable, the getstate dunder method can be defined to help out. For Pydantic, there's a couple of ways... aliases in particular seem designed to help: there's a serialization_alias argument to the Field function.