'How to take json input and do simple calculation and return value using Flask [duplicate]
The API input is like
{
"Fruits": [
{
"name": "Apple",
"quantity": 2,
"price": 24
},
{
"name": "Banana",
"quantity": 1,
"price": 17
}
],
}
when we give this JSON input to the API it has to calculate the order and The response should be like
{'order_total':41}
Solution 1:[1]
sum(fruit["price"] for fruit in fruit_dict["Fruits"])
if you want it in a result dict:
result_dict = {}
result_dict["order_total"] = sum(fruit["price"] for fruit in fruit_dict["Fruits"])
Solution 2:[2]
I think you made a mistake in order total.
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)}")
Here the output that i got
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$
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | UnsignedFoo |
| Solution 2 | Nabil |
