python使用json序列化datetime类型问题处理,jsondatetime,使用python的jso
python使用json序列化datetime类型问题处理,jsondatetime,使用python的jso
使用python的json模块序列化时间或者其他不支持的类型时会抛异常,例如下面的代码:
# -*- coding: cp936 -*-from datetime import datetimeimport jsonif __name__=='__main__': now = datetime.now() json.dumps({'now':now})
运行会出现下面的错误信息:
Traceback (most recent call last): File "C:\Users\xx\Desktop\t.py", line 8, in <module> json.dumps({'now':now}) File "C:\Python27\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Python27\lib\json\encoder.py", line 201, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python27\lib\json\encoder.py", line 264, in iterencode return _iterencode(o, 0) File "C:\Python27\lib\json\encoder.py", line 178, in default raise TypeError(repr(o) + " is not JSON serializable")TypeError: datetime.datetime(2012, 12, 26, 11, 51, 33, 409000) is not JSON serializable
意思是说datetime类不支持Json序列化
我们需要对json做下扩展,让它可以支持datetime类型。
class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, obj)
在调用json.dumps时需要指定cls参数为ComplexEncoder
例如:
json.dumps({'now':now}, cls=ComplexEncoder)
相关内容
- 使用urlparse.urlparse()解析url,,python中使用url
- python使用memcached做缓存,pythonmemcached,在python中使用me
- python使用SGMLParser提取文本正文内容,pythonsgmlparser,如下
- Python thread socket server,pythonsocket,从网上参考了一些代码
- python list使用技巧总结,pythonlist使用技巧,判断一个 l
- python dict使用技巧,pythondict,在 Dictionary
- Python统计列表中元素出现的次数,python统计列表元素
- Python yield使用示例,pythonyield示例,下面2段代码通过Py
- python使用eval,exec将字符串(string)转为字典(dict),pythone
- Python POP3 收取邮件,pythonpop3,python 为我们提供
评论关闭