RyanHuddart20
RyanHuddart20

Reputation: 1

getting json data that is inside a bracket

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 data inside nutrients?

Upvotes: 0

Views: 1421

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

It returns a dictionary, but you can use the default return on dict.get to avoid any attribute errors:

nutrients = response.json().get('nutrition', {}).get('nutrients')

This way, if nutrition isn't there, you won't get something like NoneType has no attribute 'get'

EDIT: Now, nutrients should probably be a list here, so to get each element:

for nutrient in nutrients:
    print(nutrient['name'])

To collect them all in a list, you could do:

nutrient_names = [nutrient['name'] for nutrient in nutrients]

This still assumes that the name key is always present for each nutrient. To avoid errors that may result from nutrient returning None, you could do:

# add an empty list as a default return
nutrients = response.json().get('nutrition', {}).get('nutrients', [])

nutrient_names = [nutrient['name'] for nutrient in nutrients]

Upvotes: 2

Related Questions