TypeError: Object of type 'datetime' is not JSON serializable

简介: TypeError: Object of type 'datetime' is not JSON serializable

json序列化时间对象的时候报错:


 

TypeError: Object of type 'datetime' is not JSON serializable

解决办法


重写json序列化类


# -*- coding: utf-8 -*-
import json
import datetime
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)
if __name__ == '__main__':
    data = {"name": "Tom", "birthday": datetime.datetime.now()}
    print(json.dumps(data, cls=DateEncoder))
    # {"name": "Tom", "birthday": "2019-06-06 17:24:19"}
相关文章
|
4月前
|
JSON 数据格式 Python
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
|
5月前
|
JSON 数据格式
gson自定义Type解析json数组字符串
gson自定义Type解析json数组字符串
|
9月前
|
JSON 数据格式
TypeError: Object of type ‘float32‘ is not JSON serializable
TypeError: Object of type ‘float32‘ is not JSON serializable
130 0
|
10月前
|
JSON Java 数据格式
HttpMediaTypeNotSupportedException: Content type ‘application.yml/json;charset=UTF-8‘ not supported
HttpMediaTypeNotSupportedException: Content type ‘application.yml/json;charset=UTF-8‘ not supported
157 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
142 0
|
1月前
|
JSON 前端开发 Java
Json格式数据解析
Json格式数据解析
|
2月前
|
存储 JSON Apache
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
在最新发布的阿里云数据库 SelectDB 的内核 Apache Doris 2.1 新版本中,我们引入了全新的数据类型 Variant,对半结构化数据分析能力进行了全面增强。无需提前在表结构中定义具体的列,彻底改变了 Doris 过去基于 String、JSONB 等行存类型的存储和查询方式。
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
|
1天前
|
XML JSON API
转Android上基于JSON的数据交互应用
转Android上基于JSON的数据交互应用
|
9天前
|
JSON JavaScript Java
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
21 0
|
11天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{"name": "John", "age": 30, "city": "New York"}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
16 1