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

我正在尝试查看 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}}


斯蒂芬大帝
浏览 196回答 3
3回答

MMTTMM

你的支票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 responsemeta_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)

繁花如伊

您在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']

FFIVE

你的 if 语句没有做你认为他们正在做的事情。例如:if 'AccessKeyMetadata'应该:if response['AccessKeyMetadata']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python