datetime.date(2014, 4, 25) is not JSON serializabl

2020-05-17 04:44发布

I followed How to overcome "datetime.datetime not JSON serializable" in python? but this is not helping

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.

5条回答
闹够了就滚
2楼-- · 2020-05-17 05:17

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

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

b = json.dumps(a, cls = DateTimeEncoder)
查看更多
家丑人穷心不美
3楼-- · 2020-05-17 05:20

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-serializable Put this in models.py right under the imports. It'll take care of UUIDs for you too.

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
查看更多
乱世女痞
4楼-- · 2020-05-17 05:25

Convert date to equivalent iso format,

In [29]: datetime.datetime.now().isoformat()
Out[29]: '2020-03-06T12:18:54.114600'
查看更多
戒情不戒烟
5楼-- · 2020-05-17 05:27

See the Extending encoder section from the json package docs 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)
查看更多
走好不送
6楼-- · 2020-05-17 05:28

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.

Update as per J.F.Sebastian comment

def date_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    else:
        raise TypeError

print json.dumps(data, default=date_handler)
查看更多
登录 后发表回答