프로그래밍/Python
Pydantic Serialize시 오류 : Object of type <Enum> is not JSON serializable 해결방법
Lou Park
2025. 3. 28. 16:23
공식문서 참조: https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.use_enum_values
Enum을 Enum 값으로 사용할지 여부를 정의할 수 있는 use_enum_values
라는 Model Configuration을 True
로 설정할 경우에 Serialize 가능해진다.
class SomeEnum(Enum):
FOO = 'foo'
BAR = 'bar'
BAZ = 'baz'
class SomeModelCls(BaseModel):
e: SomeEnum
m = SomeModelCls(e=SomeEnum.FOO)
m.model_dump() # TypeError: Object of type SomeEnum is not JSON serializable
FIX:
class SomeModelCls(BaseModel, use_enum_values=True):
e: SomeEnum
m = SomeModelCls(e=SomeEnum.FOO)
m.model_dump() # No Error