TypeError:datetime.datetime不是JSON可序列化的

时间:2018-06-08 14:47:20

标签: python json amazon-web-services datetime time

我正在学习Python和aws。

我想要的是从JSON响应中提取值。此代码适用于不包含日期值的JSON响应,但在这种情况下,响应包含日期值。

这是我的代码:

import datetime
from datetime import date, datetime
import boto3
import json

client = boto3.client('lex-models')

response = client.get_utterances_view(
          botName='CreateServicesBot',
          botVersions=[
                     '$LATEST',
                      ],
          statusType='Missed'
          )

with open('/tmp/output.json', 'w') as data:
          json.dump(response,data)

with open('/tmp/output.json') as f:
          data = json.load(f)
ustr=data["utteranceString"]
print ustr

我收到此错误:

  

TypeError: datetime.datetime(2018, 6, 7, 9, 44, 38, 146000, tzinfo=tzlocal()) is not JSON serializable

有人知道解决方案吗? THX

2 个答案:

答案 0 :(得分:3)

因为错误暗示你试图将datetime.datetime对象转储到json中,这是不可能的。

您可以做的是将这些对象转换为字符串然后转储它。假设包含datetime.datetime的字段被称为date,那么您需要在导出到json文件之前执行以下操作

response[date] = response[date].strftime("%Y-%m-%d %H:%M:%S")

答案 1 :(得分:-3)

我按你的要求做了

import datetime
from datetime import date, datetime
import boto3
import json

client = boto3.client('lex-models')

response = client.get_utterances_view(
    botName='CreateServicesBot',
    botVersions=[
        '$LATEST',
    ],
    statusType='Missed'
)
response[lastUtteredDate] = response[lastUtteredDate].strftime("%Y-%m-%d 
%H:%M:%S")
response[firstUtteredDate] = response[firstUtteredDate].strftime("%Y-%m-%d 
%H:%M:%S")


with open('/tmp/output.json', 'w') as data:
    json.dump(response,data)


with open('/tmp/output.json') as f:
    data = json.load(f)
ustr=data["utteranceString"]
print ustr

我收到了这个错误

  

NameError:name' lastUtteredDate'未定义

当我打印响应时,我得到了这个(第一个块)

  

{u' matterances':[{u' matterances':[{u' count':49,u' utteranceString':u'你好',>你' lastUtteredDate ':datetime.datetime(2018,6,7,9,44,38,146000,> tzinfo = tzlocal()) ,u&different 39.Users':42,u' firstUtteredDate ':> > > datetime.datetime(2018,5,31,8,52,34,907000,tzinfo = tzlocal())},