【发布时间】:2021-10-09 11:50:34
【问题描述】:
我需要创建一个可以接收以下 JSON 并识别其中包含的对象的端点:
{
"data": [
{
"start": "A", "end": "B", "distance": 6
},
{
"start": "A", "end": "E", "distance": 4
}
]
}
我创建了一个模型来处理单个对象:
class GraphBase(BaseModel):
start: str
end: str
distance: int
有了它,我可以将它保存在数据库中。但现在我需要接收一个对象列表并将它们全部保存。 我试图做这样的事情:
class GraphList(BaseModel):
data: Dict[str, List[GraphBase]]
@app.post("/dummypath")
async def get_body(data: schemas.GraphList):
return data
但我在 FastApi 上不断收到此错误:Error getting request body: Expecting property name enclosed in double quotes: line 1 column 2 (char 1),并在响应中显示此消息:
{
"detail": "There was an error parsing the body"
}
我是 python 的新手,甚至是 FastApi 的新手,如何将该 JSON 转换为 GraphBase 列表以将它们保存在我的数据库中?
【问题讨论】:
-
data: List[GraphBase]在GraphList的定义中呢?data字段是图形库对象的列表。 -
@KotaMori 我尝试了你的建议,它返回了同样的错误。
-
您尝试过文档页面上的 API 吗?
-
@KotaMori 我尝试了所有可以在 API 文档页面上找到的方法,但没有成功。
标签: python json fastapi pydantic