Python datetime.date(2014, 4, 25) 在 Django 中不是 JSON 可序列化的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23285558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
datetime.date(2014, 4, 25) is not JSON serializable in Django
提问by Praveen Singh Yadav
I followed How to overcome "datetime.datetime not JSON serializable" in python?but this is not helping
我遵循了如何在 python 中克服“datetime.datetime not JSON serializable”?但这无济于事
I tried this code
我试过这个代码
>>> 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) is not JSON serializable
Can somebody help me with a datetime.date
serializer and deserializer.
有人可以帮助我使用datetime.date
序列化器和反序列化器。
回答by Nishant Nawarkhede
Convert date to equivalent iso format,
将日期转换为等效的iso格式,
In [29]: datetime.datetime.now().isoformat()
Out[29]: '2020-03-06T12:18:54.114600'
回答by Greg
You can add a date time encoder into the JSON jumps function when handling model querysets, this is customised a bit as I had issues with the base django model state being parsed
您可以在处理模型查询集时将日期时间编码器添加到 JSON 跳转函数中,这是自定义的,因为我在解析基本 django 模型状态时遇到了问题
import datetime
import decimal
from django.db.models.base import ModelState
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj)
elif isinstance(obj, ModelState):
return None
else:
return json.JSONEncoder.default(self, obj)
Then use this class with your json dumps
然后将此类与您的 json 转储一起使用
b = json.dumps(a, cls = DateTimeEncoder)
回答by AlexandruC
You can also do this:
你也可以这样做:
def date_handler(obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj
print json.dumps(data, default=date_handler)
From here.
从这里开始。
Updateas per J.F.Sebastian comment
根据 JFSebastian 评论更新
def date_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError
print json.dumps(data, default=date_handler)
回答by Stephen Hartzell
See the Extending encoder section from the json package docs https://docs.python.org/2/library/json.html
请参阅 json 包文档https://docs.python.org/2/library/json.html 中的扩展编码器部分
I have used this method and found it quite effective. I think this is what you are looking for.
我使用过这种方法,发现它非常有效。我想这就是你要找的。
import json
class DatetimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
json.dumps(dict,cls=DatetimeEncoder)
回答by std''OrgnlDave
I've found this to be invaluable, especially after updating Django from 1.7 to 1.9. Most of this is from the blog http://arthurpemberton.com/2015/04/fixing-uuid-is-not-json-serializablePut this in models.py right under the imports. It'll take care of UUIDs for you too.
我发现这非常宝贵,尤其是在将 Django 从 1.7 更新到 1.9 之后。其中大部分来自博客http://arthurpemberton.com/2015/04/fixing-uuid-is-not-json-serializable将其放在 models.py 中,就在导入的正下方。它也会为您处理 UUID。
from uuid import UUID
import datetime
JSONEncoder_olddefault = JSONEncoder.default
def JSONEncoder_newdefault(self, o):
if isinstance(o, UUID): return str(o)
if isinstance(o, datetime.datetime): return str(o)
return JSONEncoder_olddefault(self, o)
JSONEncoder.default = JSONEncoder_newdefault