如何解决 pydantic 模型不可 JSON 序列化的问题

Nax*_*axi 23 python pydantic orjson

我有以下 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
Run Code Online (Sandbox Code Playgroud)

当我尝试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'})
Run Code Online (Sandbox Code Playgroud)

错误 -

TypeError: Type is not JSON serializable: MyModel
Run Code Online (Sandbox Code Playgroud)

data是一个普通的Python字典,其中有一个类型为item的项目MyModel。尝试使用.json()但得到dict has no attribute json

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

Tar*_*kin 19

得到了类似的回复FastAPI,解决方法是:

return JSONResponse(content=jsonable_encoder(item), status_code=200)
Run Code Online (Sandbox Code Playgroud)

或者可以像这样:

return jsonable_encoder(item)
Run Code Online (Sandbox Code Playgroud)

哪里jsonable_encoder

from fastapi.encoders import jsonable_encoder
Run Code Online (Sandbox Code Playgroud)

更多详细信息在这里: https: //fastapi.tiangolo.com/tutorial/encoder/