简体   繁体   中英

Python JSON TypeError when parsing from response

I don't know much about python and found an example that would serve my purpose with some modifications, currently trying to parse some data from a GET request response and I keep getting this error:

"activity['parameters']['initValue']))
TypeError: list indices must be integers or slices, not strTypeError: list indices must be integers or slices, not str"

JSON response looks like this:

{'kind': 'admin#reports#usageReports', 'etag': '"xxxxxxxxx/xxxxxxxxxxxx"', 'usageReports': [{'kind': 'admin#reports#usageReport', 'date': '2019-09-01', 'etag': '"xxxxxxxxx/xxxxxxxx"', 'entity': {'type': 'CUSTOMER', 'customerId': 'xxxxxxxx'}, 'parameters': [{'name': 'gmail:num_30day_active_users', 'intValue': '1234'}]}]}

Python Code:

    result = service.customerUsageReports().get(date='2019-09-01', parameters='gmail:num_30day_active_users').execute()

    results = result.get('usageReports', [])
    if not results:
         print('No data found.')
    else:
        print('Usage:')
        for activity in results:
            print(u'{0}: {1}'.format(activity['parameters'],
                activity['parameters']['intValue']))

What needs to be changed to make it work? Thank you!

from the data you provide, the value in parameters is a list of dict

'parameters': [{'name': 'gmail:num_30day_active_users',
    'intValue': '1234'}]}  

so you need to iterate all the items in list

result = service.customerUsageReports().get(date='2019-09-01', parameters='gmail:num_30day_active_users').execute()

results = result.get('usageReports', [])
if not results:
     print('No data found.')
else:
    print('Usage:')
    for activity in results:
       for line in activity['parameters']:
          print(u'{0}: {1}'.format(activity['parameters'],
            line['initValue']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM