2006-06-30 00:42:49 +08:00
|
|
|
"""
|
|
|
|
Serialize data to/from JSON
|
|
|
|
"""
|
|
|
|
|
2012-04-30 01:58:00 +08:00
|
|
|
# Avoid shadowing the standard library json module
|
|
|
|
from __future__ import absolute_import
|
2013-07-30 01:19:04 +08:00
|
|
|
from __future__ import unicode_literals
|
2012-04-30 01:58:00 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
import datetime
|
2010-05-04 22:00:30 +08:00
|
|
|
import decimal
|
2012-04-30 01:58:00 +08:00
|
|
|
import json
|
2013-03-19 13:04:59 +08:00
|
|
|
import sys
|
2008-07-30 18:40:37 +08:00
|
|
|
|
2012-02-10 02:56:58 +08:00
|
|
|
from django.core.serializers.base import DeserializationError
|
2006-06-30 00:42:49 +08:00
|
|
|
from django.core.serializers.python import Serializer as PythonSerializer
|
|
|
|
from django.core.serializers.python import Deserializer as PythonDeserializer
|
2012-07-20 20:22:00 +08:00
|
|
|
from django.utils import six
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.timezone import is_aware
|
2008-07-30 18:40:37 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
class Serializer(PythonSerializer):
|
|
|
|
"""
|
|
|
|
Convert a queryset to JSON.
|
|
|
|
"""
|
2007-12-17 14:53:15 +08:00
|
|
|
internal_use_only = False
|
2008-07-18 11:47:27 +08:00
|
|
|
|
2014-11-09 00:08:12 +08:00
|
|
|
def _init_options(self):
|
2012-04-30 01:58:00 +08:00
|
|
|
if json.__version__.split('.') >= ['2', '1', '3']:
|
2011-12-18 07:00:41 +08:00
|
|
|
# Use JS strings to represent Python Decimal instances (ticket #16850)
|
|
|
|
self.options.update({'use_decimal': False})
|
2012-05-26 17:43:37 +08:00
|
|
|
self._current = None
|
|
|
|
self.json_kwargs = self.options.copy()
|
|
|
|
self.json_kwargs.pop('stream', None)
|
|
|
|
self.json_kwargs.pop('fields', None)
|
2013-08-31 21:05:17 +08:00
|
|
|
if self.options.get('indent'):
|
|
|
|
# Prevent trailing spaces
|
|
|
|
self.json_kwargs['separators'] = (',', ': ')
|
2014-11-09 00:08:12 +08:00
|
|
|
|
|
|
|
def start_serialization(self):
|
|
|
|
self._init_options()
|
2012-05-26 17:43:37 +08:00
|
|
|
self.stream.write("[")
|
|
|
|
|
|
|
|
def end_serialization(self):
|
|
|
|
if self.options.get("indent"):
|
|
|
|
self.stream.write("\n")
|
|
|
|
self.stream.write("]")
|
|
|
|
if self.options.get("indent"):
|
|
|
|
self.stream.write("\n")
|
|
|
|
|
|
|
|
def end_object(self, obj):
|
|
|
|
# self._current has the field data
|
|
|
|
indent = self.options.get("indent")
|
|
|
|
if not self.first:
|
|
|
|
self.stream.write(",")
|
|
|
|
if not indent:
|
|
|
|
self.stream.write(" ")
|
|
|
|
if indent:
|
|
|
|
self.stream.write("\n")
|
|
|
|
json.dump(self.get_dump_object(obj), self.stream,
|
|
|
|
cls=DjangoJSONEncoder, **self.json_kwargs)
|
|
|
|
self._current = None
|
2007-04-25 18:12:05 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
def getvalue(self):
|
2012-06-28 22:28:25 +08:00
|
|
|
# Grand-parent super
|
|
|
|
return super(PythonSerializer, self).getvalue()
|
2006-06-30 00:42:49 +08:00
|
|
|
|
2012-02-10 02:56:58 +08:00
|
|
|
|
2006-06-30 00:42:49 +08:00
|
|
|
def Deserializer(stream_or_string, **options):
|
|
|
|
"""
|
|
|
|
Deserialize a stream or string of JSON data.
|
|
|
|
"""
|
2012-08-12 02:58:45 +08:00
|
|
|
if not isinstance(stream_or_string, (bytes, six.string_types)):
|
|
|
|
stream_or_string = stream_or_string.read()
|
2012-06-08 00:08:47 +08:00
|
|
|
if isinstance(stream_or_string, bytes):
|
2012-06-15 20:41:16 +08:00
|
|
|
stream_or_string = stream_or_string.decode('utf-8')
|
2012-02-10 02:56:58 +08:00
|
|
|
try:
|
2012-08-12 02:58:45 +08:00
|
|
|
objects = json.loads(stream_or_string)
|
2012-06-15 20:41:16 +08:00
|
|
|
for obj in PythonDeserializer(objects, **options):
|
2012-02-10 02:56:58 +08:00
|
|
|
yield obj
|
2012-02-10 09:13:38 +08:00
|
|
|
except GeneratorExit:
|
|
|
|
raise
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as e:
|
2012-02-10 02:56:58 +08:00
|
|
|
# Map to deserializer error
|
2013-03-19 13:04:59 +08:00
|
|
|
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
|
2012-02-10 02:56:58 +08:00
|
|
|
|
2007-04-25 18:12:05 +08:00
|
|
|
|
2012-04-30 01:58:00 +08:00
|
|
|
class DjangoJSONEncoder(json.JSONEncoder):
|
2006-06-30 00:42:49 +08:00
|
|
|
"""
|
2007-05-21 09:29:58 +08:00
|
|
|
JSONEncoder subclass that knows how to encode date/time and decimal types.
|
2006-06-30 00:42:49 +08:00
|
|
|
"""
|
|
|
|
def default(self, o):
|
2011-11-18 21:01:06 +08:00
|
|
|
# See "Date Time String Format" in the ECMA-262 specification.
|
2006-07-31 22:59:53 +08:00
|
|
|
if isinstance(o, datetime.datetime):
|
2011-11-18 21:01:06 +08:00
|
|
|
r = o.isoformat()
|
|
|
|
if o.microsecond:
|
|
|
|
r = r[:23] + r[26:]
|
|
|
|
if r.endswith('+00:00'):
|
|
|
|
r = r[:-6] + 'Z'
|
|
|
|
return r
|
2006-07-31 22:59:53 +08:00
|
|
|
elif isinstance(o, datetime.date):
|
2011-11-18 21:01:06 +08:00
|
|
|
return o.isoformat()
|
2006-06-30 00:42:49 +08:00
|
|
|
elif isinstance(o, datetime.time):
|
2011-11-18 21:01:06 +08:00
|
|
|
if is_aware(o):
|
|
|
|
raise ValueError("JSON can't represent timezone-aware times.")
|
|
|
|
r = o.isoformat()
|
|
|
|
if o.microsecond:
|
|
|
|
r = r[:12]
|
|
|
|
return r
|
2007-05-21 09:29:58 +08:00
|
|
|
elif isinstance(o, decimal.Decimal):
|
|
|
|
return str(o)
|
2006-06-30 00:42:49 +08:00
|
|
|
else:
|
2007-05-21 09:29:58 +08:00
|
|
|
return super(DjangoJSONEncoder, self).default(o)
|
|
|
|
|
|
|
|
# Older, deprecated class name (for backwards compatibility purposes).
|
|
|
|
DateTimeAwareJSONEncoder = DjangoJSONEncoder
|