mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-11 12:17:24 +03:00
34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
|
import datetime
|
||
|
import decimal
|
||
|
from django.utils import timezone
|
||
|
from django.utils import simplejson as json
|
||
|
|
||
|
|
||
|
class JSONEncoder(json.JSONEncoder):
|
||
|
"""
|
||
|
JSONEncoder subclass that knows how to encode date/time and decimal types.
|
||
|
"""
|
||
|
def default(self, o):
|
||
|
# See "Date Time String Format" in the ECMA-262 specification.
|
||
|
if isinstance(o, datetime.datetime):
|
||
|
r = o.isoformat()
|
||
|
if o.microsecond:
|
||
|
r = r[:23] + r[26:]
|
||
|
if r.endswith('+00:00'):
|
||
|
r = r[:-6] + 'Z'
|
||
|
return r
|
||
|
elif isinstance(o, datetime.date):
|
||
|
return o.isoformat()
|
||
|
elif isinstance(o, datetime.time):
|
||
|
if timezone.is_aware(o):
|
||
|
raise ValueError("JSON can't represent timezone-aware times.")
|
||
|
r = o.isoformat()
|
||
|
if o.microsecond:
|
||
|
r = r[:12]
|
||
|
return r
|
||
|
elif isinstance(o, decimal.Decimal):
|
||
|
return str(o)
|
||
|
elif hasattr(o, '__iter__'):
|
||
|
return [i for i in o]
|
||
|
return super(JSONEncoder, self).default(o)
|