使用Python和FastApi从邮政请求中解析JSON

发布于 2025-01-28 20:59:01 字数 1238 浏览 0 评论 0原文

我正在尝试解析来自用户的帖子请求到使用FastApi制造的API的JSON。我有一个可以接收多个值的嵌套JSON,我的问题是:如何解析并从此嵌套的JSON中获取值?

JSON就是这样:

{
    "recipe": [
    {
        "ingredient": "rice",
        "quantity": 1.5
        },
    {
        "ingredient": "carrot",
        "quantity": 1.8
        },
    {
        "ingredient": "beans",
        "quantity": 1.8
        }
    ]
}

我必须从列表配方分开的所有值,因为我有一个带有此 Ingredient的数据库,并且会查询所有这些并进行一些计算用用户给出的数量。但是我什至不知道如何从邮政请求中解析这个JSON。

我已经有2个类,pydantic验证了以下值,例如:

class Ingredientes(BaseModel):
    ingredient: str
    quantity: float


class Receita(BaseModel):
    receita: List[Ingredientes] = []

编辑1:我尝试将其包含在我的功能中,以收到此帖子请求,并且不起作用,例如:

@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:用代码bellow修复了问题(感谢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}'

I'm trying to parse a JSON that came from a POST request from user to my API made with FastAPI. I have a nested JSON that can receive multiple values and my problem is: How can I parse it and get the values from this nested JSON?

The JSON is like this:

{
    "recipe": [
    {
        "ingredient": "rice",
        "quantity": 1.5
        },
    {
        "ingredient": "carrot",
        "quantity": 1.8
        },
    {
        "ingredient": "beans",
        "quantity": 1.8
        }
    ]
}

I must grab the all values from the list recipe separated, as I have a database with this ingredient and will query all of this and do some calculates with the quantity given from user. But I don't even know how I can parse this JSON from the POST request.

I already have a 2 classes with Pydantic validating this values like:

class Ingredientes(BaseModel):
    ingredient: str
    quantity: float


class Receita(BaseModel):
    receita: List[Ingredientes] = []

Edit 1: I tried to include it in my function that recieve this POST request and didn't work like:

@app.post('/calcul', status_code=200)
def calculate_table(receita: Receita):
    receipe = receita["receita"]
    for ingredient in receipe:
        return f'{ingredient["ingredient"]}: {ingredient["quantity"]}'

Edit 2: Fixed the issue with the code bellow(Thanks 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}'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

a√萤火虫的光℡ 2025-02-04 20:59:01

要将JSON格式的字符串解析为字典中,请使用loads json json 模块的函数,例如:

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']}")

To parse a JSON-formatted string (from the POST request, for example) into a dictionary, use the loads function from the json module, like this:

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']}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文