1 from django
.db
.models
.query
import QuerySet
2 from django
.utils
import six
, timezone
3 from django
.utils
.encoding
import force_text
4 from django
.utils
.functional
import Promise
12 class JSONEncoder(json
.JSONEncoder
):
14 JSONEncoder subclass that knows how to encode date/time/timedelta,
15 decimal types, generators and other basic python objects.
17 Taken from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py
19 def default(self
, obj
):
20 # For Date Time string spec, see ECMA 262
21 # http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
22 if isinstance(obj
, Promise
):
23 return force_text(obj
)
24 elif isinstance(obj
, datetime
.datetime
):
25 representation
= obj
.isoformat()
27 representation
= representation
[:23] + representation
[26:]
28 if representation
.endswith('+00:00'):
29 representation
= representation
[:-6] + 'Z'
31 elif isinstance(obj
, datetime
.date
):
32 return obj
.isoformat()
33 elif isinstance(obj
, datetime
.time
):
34 if timezone
and timezone
.is_aware(obj
):
35 raise ValueError("JSON can't represent timezone-aware times.")
36 representation
= obj
.isoformat()
38 representation
= representation
[:12]
40 elif isinstance(obj
, datetime
.timedelta
):
41 return six
.text_type(total_seconds(obj
))
42 elif isinstance(obj
, decimal
.Decimal
):
43 # Serializers will coerce decimals to strings by default.
45 elif isinstance(obj
, uuid
.UUID
):
46 return six
.text_type(obj
)
47 elif isinstance(obj
, QuerySet
):
49 elif hasattr(obj
, 'tolist'):
50 # Numpy arrays and array scalars.
52 elif hasattr(obj
, '__getitem__'):
57 elif hasattr(obj
, '__iter__'):
58 return tuple(item
for item
in obj
)
59 return super(JSONEncoder
, self
).default(obj
)