我正在使用此代码来获取IAM用户:
#!/usr/bin/env python
import boto3
import json
client = boto3.client('iam')
response = client.list_users(
)
print response
并获得:
{u'Users': [{u'UserName': 'ja', u'Path': '/', u'CreateDate': datetime.datetime(2018, 4, 6, 12, 41, 18, tzinfo=tzutc()), u'UserId': 'AIDAJXIHXCSI62ZQKLGZM', u'Arn': 'arn:aws:iam::233135199200:user/ja'}, {u'UserName': 'test', u'Path': '/', u'CreateDate': datetime.datetime(2018, 4, 7, 10, 55, 58, tzinfo=tzutc()), u'UserId': 'AIDAIENHQD6YWMX3A45TY', u'Arn': 'arn:aws:iam::233135199200:user/test'}], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'ebd600f0-3a52-11e8-bc50-d37153ae8ac5', 'HTTPHeaders': {'x-amzn-requestid': 'ebd600f0-3a52-11e8-bc50-d37153ae8ac5', 'date': 'Sat, 07 Apr 2018 11:00:44 GMT', 'content-length': '785', 'content-type': 'text/xml'}}, u'IsTruncated': False}
我保存了对 JSON 文件的响应
我只需要提取用户名,在这种情况下输出应该是 2 行:
ja
test
添加时
print response['Users'][0]['UserName']
仅获取名字,如果设置为[]
则语法不正确
无需转换为 JSON。响应以 Python 对象的形式返回:
import boto3
client = boto3.client('iam')
response = client.list_users()
print ([user['UserName'] for user in response['Users']])
这将导致:
['ja', 'test']
或者,您可以使用:
for user in response['Users']:
print (user['UserName'])
这导致:
ja
test