簡體   English   中英

如何解決 pydantic 模型不是 JSON 可序列化的

[英]How to resolve pydantic model is not JSON serializable

我有以下 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

我被困在這里。 有人能幫我嗎。

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/

這里的問題是 pydantic 模型默認情況下不是 json 可序列化的,在您的情況下,您可以調用 data.dict() 來序列化模型的 dict 版本。

from io import BytesIO
from orjson import dumps

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

僅設置一個默認編碼器(如果其他所有方法都失敗,則使用該編碼器)怎么樣?

orjson.dumps(
    MyModel(name="asd"),
    default=lambda x: x.dict()
)
# Output: b'{"name":"asd","config1":null,"config2":null}'

或者更多嵌套:

orjson.dumps(
    {"a_key": MyModel(name="asd")}, 
    default=lambda x: x.dict()
)
# Output: b'{"a_key":{"name":"asd","config1":null,"config2":null}}'

如果您有 Pydantic 以外的其他類型,只需創建一個函數並分別處理您擁有的所有類型。

它也適用於標准庫中的json庫(對於那些不使用 orjson 的庫)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM