如何克服“datetime.datetime 不可 JSON 序列化"? [英] How to overcome "datetime.datetime not JSON serializable"?

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

问题描述

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

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 不可 JSON 序列化"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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