Home > Back-end >  Appending json to list through loop
Appending json to list through loop

Time:09-11

Can't append seperate values from json data to lists. When trying to index them, getting this kind of error :
'TypeError: 'int' object is not subscriptable'
Without showing index, its just appends ALL of the data, which i dont want.
In this part i'am getting data:

import requests
import json

protein = []
fat = []
calories = []
sugar = []

def scrape_all_fruits():
    data_list = []
    try:
        for ID in range(1, 10):
            url = f'https://www.fruityvice.com/api/fruit/{ID}'
            response = requests.get(url)
            data = response.json()
            data_list.append(data)
    except:
        pass
    return data_list

In this part iam trying to append data and getting error i've mentioned before.

alist = json.dumps(scrape_all_fruits())
jsonSTr = json.loads(alist)


for i in jsonSTr:
    try:
        for value in i['nutritions'].values():
            fat.append(value['fat'])

    except KeyError:
        pass

print(fat)

CodePudding user response:

you iterate trough the values of nutritions. So it's not possible that there is a "fat" key. And why you iterate trough it? I mean theres no reason, just take the Key.

alist = json.dumps(scrape_all_fruits())
json_str = json.loads(alist)

for i in json_str:
    try:
        print(i['nutritions'])
        fat.append(i['nutritions']['fat'])
    except KeyError:
        pass
print(fat)

This works. Tested on Python 3.8

  • Related