为什么python中的日期时间对象的json序列化对于日期时间对象不可用 [英] Why does json serialization of datetime objects in python not work out of the box for datetime objects

查看:139
本文介绍了为什么python中的日期时间对象的json序列化对于日期时间对象不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么json序列化不适用于datetime对象.据我了解json序列化,可以将任何对象的基本概念称为__str__内置函数,然后对作为响应获得的对象进行urlencode.但是在datetime的情况下,出现以下错误

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

虽然有一个__str__,即一种对已经可用的对象进行字符串化的方法,但是似乎有意识地决定不这样做,为什么会这样呢?

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?

推荐答案

不,它在json模块中不起作用.该模块为您提供默认的编码器:json.JSONEncoder.您需要扩展它,以提供default方法的实现以序列化对象.像这样:

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)

正如其他人正确指出的,原因是 json的标准没有指定日期时间如何被代表.

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

这篇关于为什么python中的日期时间对象的json序列化对于日期时间对象不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆