从JSON打印值

时间:2018-01-23 15:50:34

标签: python json boto3

Python Noob Here。我有一个列表,返回这样的项目:

"Users": [
    {
        "UserName": "Adele",
        "Path": "/",
        "CreateDate": "2013-03-07T05:14:48Z",
        "UserId": "AKIAI44QH8DHBEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:user/Adele"
    },
    {
        "UserName": "Bob",
        "Path": "/",
        "CreateDate": "2012-09-21T23:03:13Z",
        "UserId": "AKIAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:user/Bob"
    }
]

我希望能够遍历json对象并打印用户的UserNames,这些用户名为“CreateDate'是今天:

    for Users, UserName in users.items():
    print Users['CreateDate']
    if Users['CreateDate'] == datetime.today():
        print Users['UserName']

我收到错误:

"errorType": "TypeError",

"errorMessage": "string indices must be integers"

不确定我错过了什么。

2 个答案:

答案 0 :(得分:1)

正如其他人在评论中所述。您的用户数据结构是一个列表,您只需使用常规的forloop进行识别。

>>> users = {"Users": [
...     {
...         "UserName": "Adele",
...         "Path": "/",
...         "CreateDate": "2013-03-07T05:14:48Z",
...         "UserId": "AKIAI44QH8DHBEXAMPLE",
...         "Arn": "arn:aws:iam::123456789012:user/Adele"
...     },
...     {
...         "UserName": "Bob",
...         "Path": "/",
...         "CreateDate": "2012-09-21T23:03:13Z",
...         "UserId": "AKIAIOSFODNN7EXAMPLE",
...         "Arn": "arn:aws:iam::123456789012:user/Bob"
...     }
... ]}
>>> from datetime import datetime
>>> today = datetime.now()
>>> for user in users['Users']:
...     user_created = datetime.strptime(user['CreateDate'], '%Y-%m-%dT%H:%M:%SZ')
...     if user_created.year == today.year and user_created.month == 
today.month and user_created.day == today.day:
...             print(user['UserName'])
... 
>>> 

答案 1 :(得分:1)

以下是众多方法之一:

    import boto3
    import datetime
    a=boto3.client('iam')
    b=a.list_users()
    for i in b['Users']:
        x=i['CreateDate'].date()
        y=datetime.datetime.now().date()
        if x==y:
            print i['UserName']