我正在尝试处理从API获取的JSON文件。但是当我用json.loads()
转换它时,我尝试访问它的信息。我收到以下错误:
Exception Value: list indices must be integers, not str
python代码:
response = requests.get(url, params=params)
print(response.text)
results= json.loads(response.text)
result = results['results']['lists'] ['id']
JSON输出:
{"meta":{"pagination":{}},"results":[{"id":"3358","status":"ACTIVE","fax":"","addresses":[],"notes":[],"confirmed":false,"lists":[{"id":"60","status":"ACTIVE"}],"source":"API","email_addresses":[{"id":"d4ae529ce120","status":"ACTIVE","confirm_status":"NO_CONFIRMATION_REQUIRED","opt_in_source":"ACTION_BY_OWNER","opt_in_date":"2015-06-17T16:07:09.000Z","email_address":"test35@tes.com"}],"prefix_name":"","first_name":"test44","middle_name":"","last_name":"","job_title":"","company_name":"test","home_phone":"","work_phone":"","cell_phone":"","custom_fields":[],"created_date":"2015-06-17T16:07:09.000Z","modified_date":"2015-06-17T16:07:09.000Z","source_details":"Site"}]}
如何使用索引字符串访问元素,或者您建议使用哪个库来解决问题?
答案 0 :(得分:0)
results
键给出了一个对象列表:
>>> from pprint import pprint
>>> import json
>>> pprint(json.loads('''{"meta":{"pagination":{}},"results":[{"id":"3358","status":"ACTIVE","fax":"","addresses":[],"notes":[],"confirmed":false,"lists":[{"id":"60","status":"ACTIVE"}],"source":"API","email_addresses":[{"id":"d4ae529ce120","status":"ACTIVE","confirm_status":"NO_CONFIRMATION_REQUIRED","opt_in_source":"ACTION_BY_OWNER","opt_in_date":"2015-06-17T16:07:09.000Z","email_address":"test35@tes.com"}],"prefix_name":"","first_name":"test44","middle_name":"","last_name":"","job_title":"","company_name":"test","home_phone":"","work_phone":"","cell_phone":"","custom_fields":[],"created_date":"2015-06-17T16:07:09.000Z","modified_date":"2015-06-17T16:07:09.000Z","source_details":"Site"}]}''')
... )
{u'meta': {u'pagination': {}},
u'results': [{u'addresses': [],
u'cell_phone': u'',
u'company_name': u'test',
u'confirmed': False,
u'created_date': u'2015-06-17T16:07:09.000Z',
u'custom_fields': [],
u'email_addresses': [{u'confirm_status': u'NO_CONFIRMATION_REQUIRED',
u'email_address': u'test35@tes.com',
u'id': u'd4ae529ce120',
u'opt_in_date': u'2015-06-17T16:07:09.000Z',
u'opt_in_source': u'ACTION_BY_OWNER',
u'status': u'ACTIVE'}],
u'fax': u'',
u'first_name': u'test44',
u'home_phone': u'',
u'id': u'3358',
u'job_title': u'',
u'last_name': u'',
u'lists': [{u'id': u'60', u'status': u'ACTIVE'}],
u'middle_name': u'',
u'modified_date': u'2015-06-17T16:07:09.000Z',
u'notes': [],
u'prefix_name': u'',
u'source': u'API',
u'source_details': u'Site',
u'status': u'ACTIVE',
u'work_phone': u''}]}
请注意[...]
值周围的results
方括号。
你需要使用一个循环遍历每个:
for result in results['results']:
print result['id']
或使用索引来处理特定条目:
print results['result'][0]['id']
没有'lists'
密钥。
请注意requests
库本身可以处理JSON数据;这里不需要使用json
库:
response = requests.get(url, params=params)
results = response.json()