Python 获取datetime的JSON可序列化错误

Python 获取datetime的JSON可序列化错误,python,json,amazon-web-services,amazon-cloudformation,Python,Json,Amazon Web Services,Amazon Cloudformation,我正在尝试使用boto3获取CloudFormation堆栈的详细信息,如下所示 import boto3 import json def lambda_handler(event, context): global cnfOutput cnfOutput = cfn1.describe_stacks(StackName='cfn-init-stack1') cnf2 = json.dumps(cnfOutput) return cnf2 下面是我打印cfnO

我正在尝试使用boto3获取CloudFormation堆栈的详细信息,如下所示

import boto3
import json

def lambda_handler(event, context):
    global cnfOutput
    cnfOutput = cfn1.describe_stacks(StackName='cfn-init-stack1')
    cnf2 = json.dumps(cnfOutput)
    return cnf2
下面是我打印cfnOutput时得到的输出。我试图做json.dumps并得到错误。需要帮助吗

{u'Stacks': [{u'StackId': 'arn:aws:cloudformation:us-west-2:123456789123:stack/cfn-init-stack1/d209-11e8-b83e-0ad6ed005066', u'Description': 'CloudFormation template for creating an ec2 instance', u'Parameters': [{u'ParameterValue': 'e1', u'ParameterKey': 'KeyName'}, {u'ParameterValue': 'ami-a0cfeed8', u'ParameterKey': 'ImageId'}, {u'ParameterValue': 't2.micro', u'ParameterKey': 'InstanceType'}], u'Tags': [], u'Outputs': [{u'Description': 'The public name of the EC2 instance.', u'OutputKey': 'PublicName', u'OutputValue': 'ec2-51-111-211-211.us-west-2.compute.amazonaws.com'}], u'RoleARN': 'arn:aws:iam::123456789123:role/CFN1-role', u'EnableTerminationProtection': False, u'CreationTime': datetime.datetime(2018, 10, 17, 12, 40, 10, 783000, tzinfo=tzlocal()), u'StackName': 'cfn-init-stack1', u'NotificationARNs': ['arn:aws:sns:us-west-2:123456789123:topic2'], u'StackStatus': 'CREATE_COMPLETE', u'DisableRollback': False, u'RollbackConfiguration': {u'RollbackTriggers': []}}], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'd20e-11e8-b15b-a11f0bf7ba', 'HTTPHeaders': {'x-amzn-requestid': 'd20e-11e8-b15b-a11f0bf7ba', 'date': 'Wed, 17 Oct 2018 13:13:11 GMT', 'content-length': '2010', 'content-type': 'text/xml'}}}
低于错误值

默认情况下,文件“/usr/lib64/python2.7/json/encoder.py”第184行 raise TypeError(repr(o)+“不可JSON序列化”)TypeError:datetime.datetime(2018,10,17,12,40,10,783000,tzinfo=tzlocal()) JSON不可序列化


如何将原始字典转换为JSON

以下内容对我来说没有任何问题:

j = json.dumps({"key": str(datetime.datetime(2017, 10, 12, 12, 40, 10, 783000))})
但是,当我以以下方式运行它时:

j = json.dumps({"key": datetime.datetime(2017, 10, 12, 12, 40, 10, 783000)})
我犯了和你一样的错误

如果您可以在调用
json.dumps
之前将
datetime.datetime(2018,10,17,12,40,10,783000,tzinfo=tzlocal())的结果转换为字符串,则应该可以解决您的问题

如何从原始字典中提取OutputValue

# d is your original dictionary
# after you convert the datetime.datetime() result to string
d = {
    u'Stacks': [{
        u'StackId': 'arn:aws:cloudformation:us-west-2:123456789123:stack/cfn-init-stack1/d209-11e8-b83e-0ad6ed005066', 
        u'Description': 'CloudFormation template for creating an ec2 instance', u'Parameters': [{
            u'ParameterValue': 'e1', u'ParameterKey': 'KeyName'
        }, {
            u'ParameterValue': 'ami-a0cfeed8', u'ParameterKey': 'ImageId'
        }, {
            u'ParameterValue': 't2.micro', u'ParameterKey': 'InstanceType'
        }], u'Tags': [], u'Outputs': [{
            u'Description': 'The public name of the EC2 instance.', u'OutputKey': 'PublicName', u'OutputValue': 'ec2-51-111-211-211.us-west-2.compute.amazonaws.com'
        }], u'RoleARN': 'arn:aws:iam::123456789123:role/CFN1-role', u'EnableTerminationProtection': False, u'CreationTime': str(datetime.datetime(2018, 10, 17, 12, 40, 10, 783000)), u'StackName': 'cfn-init-stack1', u'NotificationARNs': ['arn:aws:sns:us-west-2:123456789123:topic2'], u'StackStatus': 'CREATE_COMPLETE', u'DisableRollback': False, u'RollbackConfiguration': {
            u'RollbackTriggers': []
        }
    }], 
    'ResponseMetadata': {
        'RetryAttempts': 0,
        'HTTPStatusCode': 200,
        'RequestId': 'd20e-11e8-b15b-a11f0bf7ba',
        'HTTPHeaders': {
            'x-amzn-requestid': 'd20e-11e8-b15b-a11f0bf7ba',
            'date': 'Wed, 17 Oct 2018 13:13:11 GMT',
            'content-length': '2010',
            'content-type': 'text/xml'
        }
    }
}

stacks = d.get("Stacks")

if stacks == None:
    print("Key not in dictionary")
else:
    for s in stacks:
        outputs = s.get("Outputs")
        if outputs == None:
            continue

        for o in outputs:
            print(o.get("OutputValue"))

当使用您所问的词典时(将
datetime.datetime()转换为字符串后,但在将整个词典转换为JSON之前),我的输出是
ec2-51-111-211-211.us-west-2.compute.amazonaws.com
。所以,请告诉我怎么做。当你将字典转换为JSON时,它将是一个字符串对象,因此,如果你先提取值,然后将其转换为JSON,效果会更好。我不确定上述内容是否是你想要的,但请看一看。在
cfn1.description_stacks
方法中,尝试在字典中以字符串形式返回
datetime.datetime()
的结果。如果您能做到这一点,那么以上就是如何提取
“OutputValue”
我将使用
datetime.strftime(datetime\u格式)
进行转换。这将允许取消转换使用
datetime.strtime(datetime\u格式)