我试图解析来自用户的POST请求到我使用FastAPI制作的API的JSON。我有一个可以接收多个值的嵌套JSON,我的问题是:我如何解析它并从这个嵌套JSON中获取值?
JSON是这样的:
{
"recipe": [
{
"ingredient": "rice",
"quantity": 1.5
},
{
"ingredient": "carrot",
"quantity": 1.8
},
{
"ingredient": "beans",
"quantity": 1.8
}
]
}
我必须从列表中抓取所有值配方分开,因为我有一个数据库与此成分,并将查询所有这一切,并做一些计算与用户给出的数量。但是我甚至不知道如何从POST请求中解析这个JSON。
我已经有两个类Pydantic验证这些值,如:
class Ingredientes(BaseModel):
ingredient: str
quantity: float
class Receita(BaseModel):
receita: List[Ingredientes] = []
编辑1:我试图将其包含在我的函数中,接收此POST请求,但没有像:
@app.post('/calcul', status_code=200)
def calculate_table(receita: Receita):
receipe = receita["receita"]
for ingredient in receipe:
return f'{ingredient["ingredient"]}: {ingredient["quantity"]}'
编辑2:修复了下面代码的问题(谢谢MatsLindh):
@app.post('/calcul', status_code=200)
def calculate_table(receita: Receita):
receipe = receita.receita
for ingredient in receipe:
return f'{ingredient.ingrediente}: {ingredient.quantidade}'
要将json格式的字符串(例如来自POST请求)解析为字典,请使用json
模块中的loads
函数,如下所示:
import json
s = """{
"recipe": [
{
"ingredient": "rice",
"quantity": 1.5
},
{
"ingredient": "carrot",
"quantity": 1.8
},
{
"ingredient": "beans",
"quantity": 1.8
}
]
}
"""
recipe = json.loads(s)["recipe"]
for ingredient in recipe:
print(f"{ingredient['ingredient']}: {ingredient['quantity']}")