python - 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
有人知道解决方案吗?谢谢
解决方案
由于错误表明您正在尝试将datetime.datetime
对象转储到 json 中,但这是不可能的。
您可以做的是将这些对象转换为字符串,然后转储它。假设包含 a 的字段datetime.datetime
被调用date
,那么您需要在导出到json
文件之前执行以下操作
response[date] = response[date].strftime("%Y-%m-%d %H:%M:%S")
推荐阅读
- android - 将 BroadcastReceiver 重塑为 JobScheduler
- javascript - 在 Angular 中向 Node.js 发布请求未发送
- python - 将 tf.data.Dataset 和 NumPy 数组提供给模型
- jsf - 试图让这个条件起作用。如何设置此变量?
- excel - 如何在 VBA 中使用日期变量
- powerbi - Power BI 自定义连接器日志记录未发生
- logging - 是否可以选择要在 ELK UI 中显示的特定日志文件?
- wget - wget spider 一个网站收集所有链接
- maven - gradle init 不适用于 pom.xml 中的某些插件
- c# - 有没有办法使用 C# 逐步执行 Windows Workflow Foundation?