python嵌套json ararys

2024-09-19 23:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在访问一个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

如果我的理解是正确的,[]是一个列表,{}是一个对象?所以我试图访问一个对象作为一个列表,这就是为什么它不工作

对于新手来说,筑巢的数量是很难理解的。有人能解释一下并告诉我如何访问该通话策略中的每个用户吗

谢谢


Tags: nameinhttpsapiforoncallheaders
1条回答
网友
1楼 · 发布于 2024-09-19 23:31:42

根据API documentation,在user下有一个对象(想想“dictionary”):

...
"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

相关问题 更多 >