Sujet : Re: Serializing pydantic enums
De : larry.martell (at) *nospam* gmail.com (Larry Martell)
Groupes : comp.lang.pythonDate : 29. May 2024, 21:27:04
Autres entêtes
Message-ID : <mailman.69.1717010863.2909.python-list@python.org>
References : 1 2 3
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.
On Tue, May 28, 2024 at 2:50 PM Larry Martell via Python-list
<python-list@python.org> wrote:
>
Just getting started with pydantic. I have this example code:
>
class FinishReason(Enum):
stop = 'stop'
>
class Choice(BaseModel):
finish_reason: FinishReason = Field(...)
>
>
But I cannot serialize this:
>
json.dumps(Choice(finish_reason=FinishReason.stop).dict())
*** TypeError: Object of type FinishReason is not JSON serializable
>
>
I get the object not the value:
>
(Pdb) Choice(finish_reason=FinishReason.stop)
Choice(finish_reason=<FinishReason.stop: 'stop'>)
>
>
Also tried it with .value, same result.
>
What am I missing here?