【问题标题】:Cant parse boto3 client json response using python无法使用python解析boto3客户端json响应
【发布时间】:2017-02-23 16:33:30
【问题描述】:

我是 Python 语言的新手。我需要使用 Boto 3Python 获取所有 Amazon-Web-Services Identity and Access Management (Amazon-IAM) 政策详情。 p>

我尝试解析 Boto 3 客户端的 JSON 输出,还需要将 key-value 对保存到地图(policyName,Arn)中。示例 JSON 输出如下所示:

{
    'ResponseMetadata': {
        'HTTPStatusCode': 200,
        'HTTPHeaders': {
            'vary': 'Accept-Encoding',
            'content-length': '19143',
            'content-type': 'text/xml',
            'date': 'Thu, 23 Feb 2017 06:39:25 GMT'
        }
    },
    u 'Books': [ {
        u 'PolicyName': 'book1',
        u 'Arn': '002dfgdfgdfgdfgvdfxgdfgdfgdfgfdg',
        u 'CreateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc()),
        u 'UpdateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc())
    }, {
        u 'PolicyName': 'book2','
        u 'Arn': '002dfgdfgdfgdfgvdfxgdfgdfgdfgfdg',
        u 'CreateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc()),
        u 'UpdateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc())
    }]
}

我有以下代码

iampolicylist_response = iamClient.list_policies(
    Scope='Local',
    MaxItems=150
)
    print iampolicylist_response
    res=json.dumps(iampolicylist_response)
print res
ret={}
for i in res["PolicyName"]:
  ret[i["PolicyName"]]=i["Arn"]
return ret  

使用json.loads,会出现这样的错误

TypeError:预期的字符串或缓冲区

使用json.dumps,会出现这样的错误

TypeError: datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo=tzutc()) 不是 JSON 可序列化的

什么是实际问题?

【问题讨论】:

  • res=json.dumps(iampolicylist_response) 将对象转换为json字符串。

标签: python json amazon-web-services amazon-iam boto3


【解决方案1】:

结果iampolicylist_response已经是字典了

你不需要解析它。

http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.list_policies

响应是一个字典对象

删除res=json.dumps(iampolicylist_response)

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 2019-08-01
    • 2020-09-01
    • 2016-10-10
    • 2021-10-21
    • 2019-05-17
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多