无法使用 python 解析 boto3 客户端 json 响应

Cant parse boto3 client json response using python

我是 Python 语言的新手。我需要使用 Boto 3 获取所有 Amazon-Web-Services Identity and Access Management (Amazon-IAM) 策略详细信息Python.

我试图解析来自 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: expected string or buffer

使用json.dumps,显示错误如下

TypeError: datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo=tzutc()) is not JSON serializable

什么是实际问题?

结果iampolicylist_response已经是字典

您不需要解析它。

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

响应是一个字典对象

删除res=json.dumps(iampolicylist_response)