Serializing pydantic enums

Larry Martell larry.martell at gmail.com
Tue May 28 08:48:22 EDT 2024


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?


More information about the Python-list mailing list