Ticket #3324: serializers_json-Handle_Decimal.diff
File serializers_json-Handle_Decimal.diff, 1.7 KB (added by , 18 years ago) |
---|
-
django/core/serializers/json.py
16 16 Convert a queryset to JSON. 17 17 """ 18 18 def end_serialization(self): 19 simplejson.dump(self.objects, self.stream, cls=D ateTimeAwareJSONEncoder, **self.options)19 simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) 20 20 21 21 def getvalue(self): 22 22 return self.stream.getvalue() … … 32 32 for obj in PythonDeserializer(simplejson.load(stream)): 33 33 yield obj 34 34 35 class D ateTimeAwareJSONEncoder(simplejson.JSONEncoder):35 class DjangoJSONEncoder(simplejson.JSONEncoder): 36 36 """ 37 37 JSONEncoder subclass that knows how to encode date/time types 38 and Decimal objects. 38 39 """ 39 40 40 41 DATE_FORMAT = "%Y-%m-%d" 41 42 TIME_FORMAT = "%H:%M:%S" 42 43 43 44 def default(self, o): 45 decimal_available = False 46 try: 47 import decimal 48 decimal_available = True 49 except: 50 # decimal is not included in Python 2.3 51 pass 52 44 53 if isinstance(o, datetime.datetime): 45 54 return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) 46 55 elif isinstance(o, datetime.date): 47 56 return o.strftime(self.DATE_FORMAT) 48 57 elif isinstance(o, datetime.time): 49 58 return o.strftime(self.TIME_FORMAT) 59 elif decimal_available and isinstance(o, decimal.Decimal): 60 return str(o) 50 61 else: 51 return super(D ateTimeAwareJSONEncoder, self).default(o)62 return super(DjangoJSONEncoder, self).default(o)