如何克服"datetime.datetime无法JSON序列化"? [英] How to overcome "datetime.datetime not JSON serializable"?
问题描述
我的基本要求如下:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
当我尝试执行jsonify(sample)
时,我得到:
When I try to do jsonify(sample)
I get:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
我该怎么做才能使我的词典示例克服上面的错误?
What can I do such that my dictionary sample can overcome the error above?
注意:尽管可能不相关,但字典是从mongodb中检索记录生成的,在我打印出str(sample['somedate'])
时,输出为2012-08-08 21:46:24.862000
.
Note: Though it may not be relevant, the dictionaries are generated from the retrieval of records out of mongodb where when I print out str(sample['somedate'])
, the output is 2012-08-08 21:46:24.862000
.
推荐答案
已于2018年更新
原始答案适应了MongoDB日期"字段的表示方式:
Updated for 2018
The original answer accommodated the way MongoDB "date" fields were represented as:
{"$date": 1506816000000}
如果您想使用通用Python解决方案将datetime
序列化为json,请查看 @jjmontes的答案无需依赖项的快速解决方案.
If you want a generic Python solution for serializing datetime
to json, check out @jjmontes' answer for a quick solution which requires no dependencies.
由于您正在使用mongoengine(每个注释)并且pymongo是一个依赖项,因此pymongo具有内置实用程序来帮助进行json序列化:
http://api.mongodb.org/python/1.10.1 /api/bson/json_util.html
As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:
http://api.mongodb.org/python/1.10.1/api/bson/json_util.html
用法示例(序列化):
from bson import json_util
import json
json.dumps(anObject, default=json_util.default)
用法示例(反序列化):
Example usage (deserialization):
json.loads(aJsonString, object_hook=json_util.object_hook)
Django
Django提供了本机DjangoJSONEncoder
序列化程序,可以正确处理这种情况.
Django
Django provides a native DjangoJSONEncoder
serializer that deals with this kind of properly.
请参见 https://docs.djangoproject.com/en/dev/topic/serialization/#djangojsonencoder
from django.core.serializers.json import DjangoJSONEncoder
return json.dumps(
item,
sort_keys=True,
indent=1,
cls=DjangoJSONEncoder
)
我注意到DjangoJSONEncoder
和使用自定义default
之间的一个区别是这样的:
One difference I've noticed between DjangoJSONEncoder
and using a custom default
like this:
import datetime
import json
def default(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
return json.dumps(
item,
sort_keys=True,
indent=1,
default=default
)
是Django剥离了一些数据吗?
Is that Django strips a bit of the data:
"last_login": "2018-08-03T10:51:42.990", # DjangoJSONEncoder
"last_login": "2018-08-03T10:51:42.990239", # default
因此,在某些情况下,您可能需要注意这一点.
So, you may need to be careful about that in some cases.
这篇关于如何克服"datetime.datetime无法JSON序列化"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!