【问题标题】:TypeError: datetime.datetime is not JSON serializable [duplicate]TypeError:datetime.datetime 不是 JSON 可序列化的 [重复]
【发布时间】:2018-11-18 15:57:36
【问题描述】:

我正在学习 Python 和 aws。

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

这是我的代码:

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

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

【问题讨论】:

  • 下次发帖前请使用搜索功能。
  • 您好,这没有回答我的问题,我无法解决。
  • json.dumps(d, default=str) 将完成这项工作。 'default' 参数有助于将不可序列化的对象转换/转换为给定的类型/函数

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


【解决方案1】:

正如错误所暗示的,您正在尝试将 datetime.datetime 对象转储到 json 中,这是不可能的。

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

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

【讨论】:

    【解决方案2】:

    我按照你的要求做了

    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' 未定义

    当我打印 response 我得到了这个(第一块)

    {u'utterances': [{u'utterances': [{u'count': 49, u'utteranceString': u'hello', >u'lastUtteredDate': 日期时间。 datetime(2018, 6, 7, 9, 44, 38, 146000, >tzinfo=tzlocal()), u'distinctUsers': 42, u'firstUtteredDate': > > >datetime.datetime( 2018, 5, 31, 8, 52, 34, 907000, tzinfo=tzlocal())},

    【讨论】:

    • 请不要使用答案发布 cmets。
    • 评论区不支持太多字符
    • @Beastn 这应该作为问题的更新发布。未发布为答案。
    • 只需将lastUtteredDate 替换为'lastUtteredDate'
    猜你喜欢
    • 2016-06-05
    • 2016-06-22
    • 2015-09-21
    • 2014-04-12
    • 2016-12-20
    • 2019-06-01
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多