Code

Ticket #3324: serializers_json-Handle_Decimal.diff

File serializers_json-Handle_Decimal.diff, 1.7 KB (added by Jorge Gajon <gajon@…>, 7 years ago)

Patches core/serializers/json.py instead of patching the bundled simplejson library.

Line 
1Index: django/core/serializers/json.py
2===================================================================
3--- django/core/serializers/json.py     (revision 4752)
4+++ django/core/serializers/json.py     (working copy)
5@@ -16,7 +16,7 @@
6     Convert a queryset to JSON.
7     """
8     def end_serialization(self):
9-        simplejson.dump(self.objects, self.stream, cls=DateTimeAwareJSONEncoder, **self.options)
10+        simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options)
11         
12     def getvalue(self):
13         return self.stream.getvalue()
14@@ -32,20 +32,31 @@
15     for obj in PythonDeserializer(simplejson.load(stream)):
16         yield obj
17         
18-class DateTimeAwareJSONEncoder(simplejson.JSONEncoder):
19+class DjangoJSONEncoder(simplejson.JSONEncoder):
20     """
21     JSONEncoder subclass that knows how to encode date/time types
22+    and Decimal objects.
23     """
24     
25     DATE_FORMAT = "%Y-%m-%d"
26     TIME_FORMAT = "%H:%M:%S"
27     
28     def default(self, o):
29+       decimal_available = False
30+       try:
31+            import decimal
32+            decimal_available = True
33+       except:
34+            # decimal is not included in Python 2.3
35+            pass
36+
37         if isinstance(o, datetime.datetime):
38             return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
39         elif isinstance(o, datetime.date):
40             return o.strftime(self.DATE_FORMAT)
41         elif isinstance(o, datetime.time):
42             return o.strftime(self.TIME_FORMAT)
43+       elif decimal_available and isinstance(o, decimal.Decimal):
44+            return str(o)
45         else:
46-            return super(DateTimeAwareJSONEncoder, self).default(o)
47+            return super(DjangoJSONEncoder, self).default(o)