获取TypeError:字符串索引必须是Python中的整数

时间:2018-03-30 07:23:41

标签: python python-3.x

我正在尝试使用网站上的API获取数据。 Thousandeyes API

我的代码如下:

import requests
import json
import urllib2, base64
import sys

proxy = urllib2.ProxyHandler({'https': 'http://proxy.wdf.sap.corp:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)

username='xxx@xxx.com' # API Username
password='xxxxxxxxxxxxxxxxxxx' # API Password Token Code
THOUSANDEYES_API_URL='https://api.thousandeyes.com/v6/usage.json'


request = urllib2.Request(THOUSANDEYES_API_URL)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
data = json.load(result)

#save output in text file

orig_stdout = sys.stdout
f = open ('usage.txt', 'w')
sys.stdout = f

#print data

for i in data['usage']:
        print "Month Start: " + i['monthStart']
        print "Month End: " + i['monthEnd']
        print "Account Group Name:  " + i['accountGroupName']
        print "Test Name: " + i['testName']
        print "\n"

sys.stdout = orig_stdout
f.close()

当我运行此脚本时,我得到以下提示错误:

  

回溯(最近一次调用最后一次):文件“./te_license_usage.py”,   第32行,在       print“Month Start:”+ i ['monthStart'] TypeError:字符串索引必须是整数

请建议解决方案。

2 个答案:

答案 0 :(得分:0)

data['usage']包含一个列表,如错误所示:

 print "Month Start: " + i['monthStart'] TypeError: string indices must be integers

所以请使用data['usage'][0]

for i in data['usage'][0]:
    print "Month Start: " + i['monthStart']
    print "Month End: " + i['monthEnd']
    print "Account Group Name:  " + i['accountGroupName']
    print "Test Name: " + i['testName']
    print "\n"

答案 1 :(得分:-1)

您无需迭代data。它不是列表。

<强>尝试:

print "Month Start: " + data['usage']["quota"]['monthStart']         #Key "quota"
print "Month Start: " + data['usage']["quota"]['monthEnd']
for j in data['usage']['tests']:                                     #Iterate Key 'tests'
    print "Account Group Name:  " + j['accountGroupName']
    print "Test Name: " + j['testName']

<强>输出:

Month Start: 2016-04-28 00:00:00
Month Start: 2016-05-28 00:00:00
Account Group Name:  Documentation
Test Name: https://app.thousandeyes.com
Account Group Name:  Documentation
Test Name: https://support.thousandeyes.com