我正在访问API,请在此处进行示例(https://developer.pagerduty.com/documentation/rest/escalation_policies/on_call)
SUBDOMAIN='XXX'
API_ACCESS_KEY='XXX'
headers = {
'Authorization': 'Token token={0}'.format(API_ACCESS_KEY),
'Content-type': 'application/json',
}
url = 'https://{0}.pagerduty.com/api/v1/escalation_policies/on_call'.format(SUBDOMAIN)
r = requests.get(url,headers=headers)
objData = r.json()
for objPolicy in objData['escalation_policies']:
print objPolicy['name']
for objOnCall in objPolicy['on_call']:
print objOnCall['level']
print objOnCall['start']
print objOnCall['end']
for objUser in objOnCall['user']:
print objUser['name']
我目前正在收到错误
print objUser['name']
TypeError: string indices must be integers
如果我的理解是正确的,[]是一个列表,{}是一个对象?所以我试图访问一个对象作为列表,为什么它不工作?
对于新手来说,嵌套的数量很难理解。有人可以解释并告诉我如何通过on_call政策访问每个用户吗?
由于
答案 0 :(得分:1)
根据API documentation,user
下有一个对象(想想“字典”):
...
"user": {
"id": "P9TX7YH",
"name": "Cordell Simonis",
"email": "email_1@acme.pagerduty.dev",
"time_zone": "Pacific Time (US & Canada)",
"color": "dark-goldenrod"
}
要反映这一点,请将您的代码修改为:
user = objOnCall['user'] # user is a dictionary
print(user['name']) # getting a value from a dictionary by a key