fastapi如何读取嵌套的json作为字典?

问题描述

我正在尝试接收以下JSON:

{
    "va": "{1: 5,2:1,3:5}"
}

在main.py中,我有以下内容

from typing import Optional,Dict
from fastapi import FastAPI
from pydantic import BaseModel

class rq(BaseModel):
    va: Dict[str,str]
    

app = FastAPI(debug=True)

@app.post("/hello")
async def create_item(rq: rq):
    return 1

但我知道

“ msg”:“值不是有效的字典”, “ type”:“ type_error.dict”

我怎样才能收到va的指示以对其进行迭代?

解决方法

创建模型时,每个字段实际上都是一个键值对,因此在您的示例中,它期望如下所示:

{
    "va": {"some":"value"}
}

但是您发送的是

"va": str

所以我不知道您如何发送值,但是您肯定是在发送 str 而不是Dict[str,str]