Why does the json serialization not work for datetime objects . As I understand json serialization the basic idea for any object can be call the __str__ builtin function and then urlencode the object that you get as a response. But in case of datetime i get the following error

TypeError: datetime.datetime(2012, 5, 23, 18, 38, 23, 37566) is not JSON serializable

while there is a __str__ i.e a way of stringifying the object already available , But it seems like a conscious decision to not do it , why would that be the case?

推荐答案

No it doesn't work that way in json module. The module provides you with a default encoder: json.JSONEncoder. You need to extend this to provide your implementation of default method to serialize objects. Something like this:

import json
import datetime
from time import mktime

class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return int(mktime(obj.timetuple()))

        return json.JSONEncoder.default(self, obj)

print json.dumps(obj, cls=MyEncoder)

As others correctly pointed out, the reason is that the standard for json does not specify how date time can be represented.

Json相关问答推荐

两种情况下过滤的JOLT规范

使用Jolt库对多个数组进行嵌套循环

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

时间序列的Vega Lite分组条形图

序列化从/到空值

来自json的可分析的构建报告

在 postgres 14 中将记录转换为所需的 json 格式

Rust实现:高效解析任意大小的JSON数组

如何使用 jq 将字符串数组转换为对象?

颠簸转换问题

Nifi - 忽略(或删除)JSON 的第一个数字

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

Microsoft GRAPH 查询使用端点 /deviceManagement/deviceHealthScripts 列出了一种不熟悉的检测脚本内容格式

Jolt - 在同一级别添加时组合值的问题

如何使用 gson 调用默认反序列化

哪个更好:Json 或 XML (PHP)

为不同类型的项目数组正确的 JSON Schema

确保数组中的项目属性在 Json Schema 中是唯一的?

处理 HTTP 请求正文中的可选 JSON 字段

来自 Gson 的 JSON 字符串:删除双引号