【问题标题】:fastapi how to read nested json as dictionary?fastapi如何将嵌套的json读取为字典?
【发布时间】:2020-09-11 01:30:28
【问题描述】:

我正在尝试接收以下 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 作为 dict 来迭代它?

【问题讨论】:

    标签: python-3.x fastapi pydantic


    【解决方案1】:

    当您创建一个模型时,每个字段实际上都是一个键值对,因此对于您的示例,它期望是这样的:

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

    但你发送的是

    "va": str
    

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

    【讨论】:

    • 如果您存储在 SQL Alchemy 数据库中,请存储在 JSON 列类型中。还要确保在保存之前使用 json.dumps。
    猜你喜欢
    • 2018-12-27
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2018-05-31
    • 1970-01-01
    • 2023-03-11
    • 2021-04-23
    相关资源
    最近更新 更多