samedi 7 mars 2020

Loop through API multiple parameters

I have the website's API documentation http://json-homework.task-sss.krasilnikov.spb.ru/docs/9f66a575a6cfaaf7e43177317461d057 and I am to find all the users who have studied in schools in certain city (id of which is 2). By running this code(all_users is a list with main info about users from the previous task):

school=[]
for user in all_users:
        user_id=user.get('id') 
        url = f'http://json-homework.task-sss.krasilnikov.spb.ru/api/user/get?api_key=9f66a575a6cfaaf7e43177317461d057&user_id={user_id}&fields=schools'
        data = rq.get(url)
        school=school+json.loads(data.text)["response"]
school

I get such kind of data(here is a small part of the output with many fields filled):

 {'id': 136840302,
  'first_name': 'Marina',
  'last_name': 'Kushnir',
  'is_closed': False,
  'schools': [{'id': '352496',
    'country': 1,
    'city': 57,
    'name': 'Лицей ИГУ',
    'year_from': 2015,
    'year_to': 2019,
    'class': '',
    'type': 2,
    'type_str': 'Lyceum'}]},

So I have a parameter 'city' enclosed in the parameter 'schools', and I need to extract only those users who have this parameter 'city': 2. I aldo tried this code:

school=[]
for user in all_users:
    user_id=user.get('id') 
    url = f'http://json-homework.task-sss.krasilnikov.spb.ru/api/user/get?api_key=9f66a575a6cfaaf7e43177317461d057&user_id={user_id}&fields=schools'
    data = rq.get(url)
    school=school+json.loads(data.text)["response"]
school_norm=json_normalize(school)
schools = school_norm.get('schools')
school2=[]
for i in schools:
        if "'city' : 2" in i:
            school2.append(json.loads(data.text)["response"])
sch=pd.DataFrame(school2)

but it does not accept such condition if "'city' : 2" in i:. So how can I do this task?

Aucun commentaire:

Enregistrer un commentaire