• Re: Serializing pydantic enums

    From Mats Wichmann@21:1/5 to Larry Martell via Python-list on Wed May 29 17:02:08 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@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.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)