1 """ |
1 """ |
2 Serialize data to/from JSON |
2 Serialize data to/from JSON |
3 """ |
3 """ |
4 |
4 |
5 import datetime |
5 import datetime |
|
6 import decimal |
6 from StringIO import StringIO |
7 from StringIO import StringIO |
7 |
8 |
8 from django.core.serializers.python import Serializer as PythonSerializer |
9 from django.core.serializers.python import Serializer as PythonSerializer |
9 from django.core.serializers.python import Deserializer as PythonDeserializer |
10 from django.core.serializers.python import Deserializer as PythonDeserializer |
10 from django.utils import datetime_safe |
11 from django.utils import datetime_safe |
11 from django.utils import simplejson |
12 from django.utils import simplejson |
12 |
|
13 try: |
|
14 import decimal |
|
15 except ImportError: |
|
16 from django.utils import _decimal as decimal # Python 2.3 fallback |
|
17 |
13 |
18 class Serializer(PythonSerializer): |
14 class Serializer(PythonSerializer): |
19 """ |
15 """ |
20 Convert a queryset to JSON. |
16 Convert a queryset to JSON. |
21 """ |
17 """ |
22 internal_use_only = False |
18 internal_use_only = False |
23 |
19 |
24 def end_serialization(self): |
20 def end_serialization(self): |
25 self.options.pop('stream', None) |
21 self.options.pop('stream', None) |
26 self.options.pop('fields', None) |
22 self.options.pop('fields', None) |
|
23 self.options.pop('use_natural_keys', None) |
27 simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) |
24 simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) |
28 |
25 |
29 def getvalue(self): |
26 def getvalue(self): |
30 if callable(getattr(self.stream, 'getvalue', None)): |
27 if callable(getattr(self.stream, 'getvalue', None)): |
31 return self.stream.getvalue() |
28 return self.stream.getvalue() |
36 """ |
33 """ |
37 if isinstance(stream_or_string, basestring): |
34 if isinstance(stream_or_string, basestring): |
38 stream = StringIO(stream_or_string) |
35 stream = StringIO(stream_or_string) |
39 else: |
36 else: |
40 stream = stream_or_string |
37 stream = stream_or_string |
41 for obj in PythonDeserializer(simplejson.load(stream)): |
38 for obj in PythonDeserializer(simplejson.load(stream), **options): |
42 yield obj |
39 yield obj |
43 |
40 |
44 class DjangoJSONEncoder(simplejson.JSONEncoder): |
41 class DjangoJSONEncoder(simplejson.JSONEncoder): |
45 """ |
42 """ |
46 JSONEncoder subclass that knows how to encode date/time and decimal types. |
43 JSONEncoder subclass that knows how to encode date/time and decimal types. |