Milister
Milister

Reputation: 658

Parsing boto3 output JSON

i'm using this code to get IAM user:

    #!/usr/bin/env python


    import boto3
    import json


    client = boto3.client('iam')

    response = client.list_users(

    )

    print response

and getting:

{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}

I saved response to JSON file

I need only to extract Usernames so that output should be 2 lines in this case:

ja
test

when adding

print response['Users'][0]['UserName']

get only first name, if set [] then incorrect syntax

Upvotes: 2

Views: 7262

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270294

There is no need to convert to JSON. The response comes back as a Python object:

import boto3
client = boto3.client('iam')
response = client.list_users()

print ([user['UserName'] for user in response['Users']])

This will result in:

['ja', 'test']

Or, you could use:

for user in response['Users']:
  print (user['UserName'])

This results in:

ja
test

Upvotes: 10

Related Questions