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

问题描述 投票:1回答:4

我正在尝试查看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}}
python
4个回答
1
投票

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

2
投票

你的支票

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)

0
投票

在该响应中,AccessKeyMetadata是一个项目的列表,因此索引1超出范围。


0
投票

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

if 'AccessKeyMetadata'

应该:

if response['AccessKeyMetadata']
© www.soinside.com 2019 - 2024. All rights reserved.