我正在访问 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 政策中的每个用户吗?
谢谢
最佳答案
根据API documentation ,user
下有一个对象(认为是“字典”):
...
"user": {
"id": "P9TX7YH",
"name": "Cordell Simonis",
"email": "email_1@acme.pagerduty.dev",
"time_zone": "Pacific Time (US & Canada)",
"color": "dark-goldenrod"
}
为了反射(reflect)这一点,请将代码修改为:
user = objOnCall['user'] # user is a dictionary
print(user['name']) # getting a value from a dictionary by a key
关于python 嵌套 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870887/