首页 > 解决方案 > TypeError:datetime.datetime 不是 JSON 可序列化的

问题描述

我正在学习 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

有人知道解决方案吗?谢谢

标签: pythonjsonamazon-web-servicesdatetimetime

解决方案


由于错误表明您正在尝试将datetime.datetime对象转储到 json 中,但这是不可能的。

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

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

推荐阅读