I have been using rapid api to get some data on certain food products and below is an example of the json data i got back. I have been able to get some data such as the ingredients and but where i am struggling is getting the data that are nested inside each other. My question is how would i be able to get for example the data of "amount" which is inside nutrients in python.
"ingredients": "Whole Grain Corn, Sugar, Corn Syrup, Corn Meal"
"nutrition": {
"nutrients": [
{
"name": "Calcium",
"amount": 100.0,
"unit": "mg",
"percentOfDailyNeeds": 10.0
},
{
"name": "Carbohydrates",
"amount": 23.0,
"unit": "g",
"percentOfDailyNeeds": 7.67
},
The way which i was able to get the ingredients was by doing this which worked and printed out the ingredients
ingredients = response.json().get("ingredients")
But how would i do the same thing to get specific data inside nutrients such as the "name" carbohydrates?
CodePudding user response:
It's a list
(https://docs.python.org/3/tutorial/datastructures.html).
You can access it by the index (starting at 0). So to get Carbohydrates
you would do dictName["nutrition"]["nutrients"][1]["name"]
. To get Calcium you would do dictName["nutrition"]["nutrients"][0]["name"]
.
It's probably easiest to just assign and then loop through with
nutrients = dictName["nutrition"]["nutrients"]
for nutrient in nutrients:
print(nutrient["name"])
CodePudding user response:
You can do this with a filter too, which would look something like this
carbs = list(filter(lambda x: x['name'] == 'Carbohydrates', response.json()['nutrition']['nutrients']))
Which is a bit more compact. The output you get is
[{'name': 'Carbohydrates', 'amount': 23.0, 'unit': 'g', 'percentOfDailyNeeds': 7.67}]
CodePudding user response:
Simplest solution would be to unpack your values one level at a time:
data = response.json()
nutrition = data.get("nutrition", [])
nutrients = [
item
for item in nutrition.get("nutrients", [])
if item.get("name") == "Carbohydrates"
]
if nutrients:
print(nutrients[0])
The trickiest part is working with the array. I've used list comprehension to build a new filtered list (some would prefer filter
function), and then printed an item if the list is non-empty