1

I have the following JSON structure:

{
    "Users": [
        {
            "UserName": "Administrator",  
            "CreateDate": "2018-01-26T13:07:28Z", 
            "UserId": "YYYYY", 
        }, 
        {
            "UserName": "test_user1", 
            "CreateDate": "2018-01-26T14:32:13Z", 
            "UserId": "XXXXX", 
        }, 
    ]
}

I read this file this way:

jsonIAMUsers = open('reports/1.16-IAM.json', 'r')
IAMUsers = json.load(jsonIAMUsers)
jsonIAMUsers.close()

Ho do I save the values of every UserName field into a list in order to iterate over it? I mean how can I put Administrator and test_user1 in a list?

1 Answer 1

3

Just do a list comprehension!

with open('reports/1.16-IAM.json') as jsonIAMUsers:
    IAMUsers = json.load(jsonIAMUsers)
usernames = [u['UserName'] for u in IAMUsers['Users']]

Note with part. It is context manager, which will do all file-related routine(close, etc) for you.

Default mode for open function is r, so it might be skipped.

Sign up to request clarification or add additional context in comments.

2 Comments

@Rusanov It gives me the following error: TypeError: string indices must be integers
@Riccardo, my bad, fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.