【问题标题】:How to resolve pydantic model is not JSON serializable如何解决 pydantic 模型不是 JSON 可序列化的
【发布时间】:2021-09-17 08:51:43
【问题描述】:

我有以下 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 字典,其中一个项目类型为MyModel。尝试使用.json(),但得到dict has no attribute json

我被困在这里。谁能帮帮我。

【问题讨论】:

  • 您解决了这个问题吗?

标签: python pydantic orjson


【解决方案1】:

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/

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2021-11-27
    • 1970-01-01
    • 2021-12-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多