如何克服“datetime.datetime not JSON serializable"?

How to overcome quot;datetime.datetime not JSON serializablequot;?(如何克服“datetime.datetime not JSON serializable?)

本文介绍了如何克服“datetime.datetime not JSON serializable"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的字典如下:

I have a basic dict as follows:

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}

如果您想要将 datetime 序列化为 json 的通用 Python 解决方案,请查看 @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 提供了一个原生的 DjangoJSONEncoder 序列化器,可以正确处理这种情况.


Django

Django provides a native DjangoJSONEncoder serializer that deals with this kind of properly.

参见 https://docs.djangoproject.com/en/dev/主题/序列化/#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 not JSON serializable"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何克服“datetime.datetime not JSON serializable"?

基础教程推荐