为了账号安全,请及时绑定邮箱和手机立即绑定

嵌套json的Python测试-列表索引超出范围错误

嵌套json的Python测试-列表索引超出范围错误

斯蒂芬大帝 2021-12-16 14:55:11
我正在尝试查看 boto3 命令的输出中是否存在名为“AccessKeyId”的密钥。我收到此错误:  File "aws_iam_rotate_keys.py", line 76, in delete_access_key    key2 =  response['AccessKeyMetadata'][1]['AccessKeyId']IndexError: list index out of range这是产生错误的代码:user_name = str(input("Enter a user name: "))paginator = client.get_paginator('list_access_keys')for response in paginator.paginate(UserName=user_name):    print("Raw response: ", response)     if 'AccessKeyId' and 'AccessKeyMetadata[0]':        key1 =  response['AccessKeyMetadata'][0]['AccessKeyId']        print("Key 1: ", key1)    if 'AccessKeyId' and 'AccessKeyMetadata[1]':        key2 =  response['AccessKeyMetadata'][1]['AccessKeyId']这是“响应”的内容: {'AccessKeyMetadata': [{'UserName': 'bluethundr', 'AccessKeyId': 'AKIAJNYZQ2U5LGE6ZRWQ', 'Status': 'Active', 'CreateDate': datetime.datetime(2019, 3, 25, 17, 33, 40, tzinfo=tzutc())}], 'IsTruncated': False, 'ResponseMetadata': {'RequestId': '6b3e8952-4f27-11e9-af5a-356bad8d4700', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '6b3e8952-4f27-11e9-af5a-356bad8d4700', 'content-type': 'text/xml', 'content-length': '558', 'date': 'Mon, 25 Mar 2019 17:57:13 GMT'}, 'RetryAttempts': 0}}我究竟做错了什么?如果测试正确,我该如何执行?在这个响应中可以有一个或两个键。我想编写一个涵盖两种可能性的 if 测试。如果有 2 个键,则响应如下所示并且代码不会中断: {'AccessKeyMetadata': [{'UserName': 'bluethundr', 'AccessKeyId': 'AKIAJNYZQ2U5LGE6ZRWQ', 'Status': 'Active', 'CreateDate': datetime.datetime(2019, 3, 25, 17, 33, 40, tzinfo=tzutc())}, {'UserName': 'bluethundr', 'AccessKeyId': 'AKIAJVNDVTUVFZHWSRSA', 'Status': 'Active', 'CreateDate': datetime.datetime(2019, 3, 25, 18, 8, 51, tzinfo=tzutc())}], 'IsTruncated': False, 'ResponseMetadata': {'RequestId': '16957e66-4f29-11e9-b7dc-7fcb6d606368', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '16957e66-4f29-11e9-b7dc-7fcb6d606368', 'content-type': 'text/xml', 'content-length': '771', 'date': 'Mon, 25 Mar 2019 18:09:09 GMT'}, 'RetryAttempts': 0}}
查看完整描述

3 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

你的支票


if 'AccessKeyId' and 'AccessKeyMetadata[0]':

是一个简单地测试这些常量字符串的检查。在控制台中运行此代码返回:


>>> 'AccessKeyId' and 'AccessKeyMetadata[0]'

'AccessKeyMetadata[0]'

我想你想测试响应对象:


# if response is a string and not yet parsed:

# response = json.loads(response)

# if it is already parsed, go on


# .get() with a default return value [] won't raise a KeyError

# or check with:

# if 'AccessKeyMetadata' in response

meta_data = response.get('AccessKeyMetadata', [])

if len(meta_data) == 1:

    key1 = meta_data[0].get('AccessKeyId', None)

elif len(meta_data) > 1:

    key2 = meta_data[1].get('AccessKeyId', None)


查看完整回答
反对 回复 2021-12-16
?
繁花如伊

TA贡献2012条经验 获得超12个赞

您在if子句中的检查有点令人困惑。您正在检查非空字符串,该字符串将始终返回True.


为了使其尽可能接近您当前的代码,您应该这样做:


user_name = str(input("Enter a user name: "))

paginator = client.get_paginator('list_access_keys')

for response in paginator.paginate(UserName=user_name):

    print("Raw response: ", response) 

    if len(response['AccessKeyMetadata']) and 'AccessKeyId' in response['AccessKeyMetadata'][0].keys():

        key1 =  response['AccessKeyMetadata'][0]['AccessKeyId']

        print("Key 1: ", key1)

    if len(response['AccessKeyMetadata']) > 1 and 'AccessKeyId' in response['AccessKeyMetadata'][1].keys():

        key2 =  response['AccessKeyMetadata'][1]['AccessKeyId']


查看完整回答
反对 回复 2021-12-16
?
FFIVE

TA贡献1797条经验 获得超6个赞

你的 if 语句没有做你认为他们正在做的事情。例如:


if 'AccessKeyMetadata'

应该:


if response['AccessKeyMetadata']


查看完整回答
反对 回复 2021-12-16
  • 3 回答
  • 0 关注
  • 195 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信