如何使用Flask获取json输入并进行简单的计算和返回值



API输入类似于

{
  "Fruits": [
    {
      "name": "Apple",
      "quantity": 2,
      "price": 24
    },
    {
      "name": "Banana",
      "quantity": 1,
      "price": 17
    }
  ],
}

当我们将此JSON输入提供给API时,它必须计算顺序并响应应该像

{'order_total':41}
sum(fruit["price"] for fruit in fruit_dict["Fruits"])

如果你想把它放在结果dict:中

result_dict = {}
result_dict["order_total"] = sum(fruit["price"] for fruit in fruit_dict["Fruits"])

我认为您在订单总额中犯了一个错误。

import json

json_raw = """
{
"Fruits": [
{
"name": "Apple",
"quantity": 2,
"price": 24
},
{
"name": "Banana",
"quantity": 1,
"price": 17
}
]
}
"""

data = json.loads(json_raw)
print(data)
total = 0
for fruit in data ["Fruits"]:
total += fruit["quantity"] * fruit["price"]
print(f"Total : {total}")
order = {}
order["order_total"] = total
print(f"Generated json:{json.dumps(order)}")

这里是我得到的输出

nabil@LAPTOP:~/stackoverflow$ python3 compute-total.py
{'Fruits': [{'name': 'Apple', 'quantity': 2, 'price': 24}, {'name': 'Banana', 'quantity': 1, 'price': 17}]}
Total : 65
Generated json:{"order_total": 65}
nabil@LAPTOP:~/stackoverflow$

最新更新