我有一个基本的词典如下:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
Run Code Online (Sandbox Code Playgroud)
当我尝试做的时候,jsonify(sample)我得到:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
我能做些什么,以便我的字典样本可以克服上述错误?
注意:虽然它可能不相关,但字典是从mongodb中检索记录生成的,当我打印输出时str(sample['somedate']),输出是2012-08-08 21:46:24.862000.
我跟着如何在python中克服"datetime.datetime而不是JSON serializable"?但这没有帮助
我试过这段代码
>>> import datetime
>>> a =datetime.date(2014, 4, 25)
>>> from bson import json_util
>>> b = json.dumps(a,default = json_util.default)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/home/.../python2.7/site-packages/bson/json_util.py", line 256, in default
raise TypeError("%r is not JSON serializable" % obj)
TypeError: datetime.date(2014, 4, 25) …Run Code Online (Sandbox Code Playgroud)