Serializing pydantic enums
Mats Wichmann
mats at wichmann.us
Wed May 29 19:02:08 EDT 2024
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 at 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.
More information about the Python-list
mailing list