Home > database >  Get attributes from json requests using Python for loop function
Get attributes from json requests using Python for loop function

Time:08-01

I'm not very familiar with API calls and I'm working on a Data extract project.

Giving this Json response

{'ok': True,
 'channels': [{'channel_id': 'xxx-xxxx-xxx',
   'device_type': 'ios',
   'installed': True,
   'background': True,
   'attributes': {
                  'birthdate': '2000-11-19T00:00:00',
                  'gender': 'male',
                  'zipcode': 'xxx',
                  'user_id': 'xxx-yyy-zzzz',
                  'email': '[email protected]'},
                  'created': '2021-11-11T20:38:58',
                  'opt_in': False,
                  'last_registration': '2022-05-18T19:01:14',
                  'ios': {'badge': 0, 'tz': None, 'quiettime': {'start': None, 'end': None}}
                   },
#And so on
.
.
.
.
.
, 'next_page': 'next_page_url'}

How can I get the following user attributes using a Python for loop ?

  1. user_id
  2. email
  3. gender

I tried the following code but it doesn't work:

table = pd.DataFrame(data=None, columns=['user_id','email','gender'])

for channels in response['channels']:
        for attributes in channels['attributes']:
            table = table.append({
                                  'user_id' : attributes.get('user_id'), 
                                  'email' : attributes.get('email'), 
                                  'gender' : attributes.get('gender')}
                                   , ignore_index=True)

ERROR

AttributeError: 'str' object has no attribute 'get'

Any help please?

Thanks!

Othman

CodePudding user response:

This is purely on the data what I see.

r = requests.get(API<XXX>, headers={"XXX": "XXXX"})
d1 = r.json()["attributes"]
for k in d1:
    l.append(flatten_json(k))

CodePudding user response:

You don't need to iterate over channels['attributes']. Just use channels['attributes'].get('user_id'), channels['attributes'].get('email'), etc:

table = pd.DataFrame(data=None, columns=['user_id','email','gender'])

for channel in response['channels']:
    attributes = channel['attributes']:
    table = table.append({
                          'user_id' : attributes.get('user_id'), 
                          'email' : attributes.get('email'), 
                          'gender' : attributes.get('gender')}
                           , ignore_index=True)

  • Related