python - 如何解决 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
.
我被困在这里。有人能帮我吗。
解决方案
得到了类似的FastAPI
响应问题,通过以下方式解决:
return JSONResponse(content=jsonable_encoder(item), status_code=200)
或者可以是这样的:
return jsonable_encoder(item)
哪里jsonable_encoder
是:
from fastapi.encoders import jsonable_encoder
推荐阅读
- spotfire - 如何更改数据面板属性悬停在信息上?
- c# - 如何将字符串的子字符串与正则表达式匹配
- r - 如何在 R 中将日期从 dmy 重新排列为 mdy?
- python - Python:TypeError:字符串索引必须是整数
- html - 在 HTML/CSS 中使用多个 ID 为元素着色
- angular - 在呈现 App 之前设置服务变量
- python - Z3 giving unsat result for equation Solving
- c# - 带有 C# MongoDB 驱动程序的 .NET Premitive Types
- java - 如果使用 gwt-chosen-3.0.1,GWT 编译不起作用
- excel - 如何在电子邮件中包含签名?