Python JSON TypeError when parsing from response

Question:

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!

Asked By: pyth0nnoOb

||

Answers:

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']))
Answered By: galaxyan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.