首页 > 解决方案 > 如何解决 pydantic 模型不是 JSON 可序列化的

问题描述

我有以下 pydantic 模型。

class SubModel(BaseModel):
    columns: Mapping
    key: List[str]
    required: Optional[List[str]]

    class Config:
        anystr_strip_whitespace: True
        extra: Extra.allow
        allow_population_by_field_name: True


class MyModel(BaseModel):
    name: str
    config1: Optional[SubModel]
    config2: Optional[Mapping]
    class Config:
        anystr_strip_whitespace: True
        extra: Extra.allow
        allow_population_by_field_name: True

当我试图对此做一个dumps时,我得到model is not JSON serializable

from io import BytesIO
from orjson import dumps
    
bucket = s3.Bucket(bucket_name)
bucket.upload(BytesIO(dumps(data)), key, ExtraArgs={'ContentType': 'application/json'})

错误 -

TypeError: Type is not JSON serializable: MyModel

data是一个普通的 python 字典,其中一项为 type MyModel。尝试使用.json()但得到dict has no attribute json.

我被困在这里。有人能帮我吗。

标签: pythonpydanticorjson

解决方案


得到了类似的FastAPI响应问题,通过以下方式解决:

return JSONResponse(content=jsonable_encoder(item), status_code=200)

或者可以是这样的:

return jsonable_encoder(item)

哪里jsonable_encoder是:

from fastapi.encoders import jsonable_encoder

更多细节在这里: https ://fastapi.tiangolo.com/tutorial/encoder/


推荐阅读