Ticket #3324: serializers_json-Handle_Decimal.diff

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

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

  • django/core/serializers/json.py

     
    1616    Convert a queryset to JSON.
    1717    """
    1818    def end_serialization(self):
    19         simplejson.dump(self.objects, self.stream, cls=DateTimeAwareJSONEncoder, **self.options)
     19        simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options)
    2020       
    2121    def getvalue(self):
    2222        return self.stream.getvalue()
     
    3232    for obj in PythonDeserializer(simplejson.load(stream)):
    3333        yield obj
    3434       
    35 class DateTimeAwareJSONEncoder(simplejson.JSONEncoder):
     35class DjangoJSONEncoder(simplejson.JSONEncoder):
    3636    """
    3737    JSONEncoder subclass that knows how to encode date/time types
     38    and Decimal objects.
    3839    """
    3940   
    4041    DATE_FORMAT = "%Y-%m-%d"
    4142    TIME_FORMAT = "%H:%M:%S"
    4243   
    4344    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
    4453        if isinstance(o, datetime.datetime):
    4554            return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
    4655        elif isinstance(o, datetime.date):
    4756            return o.strftime(self.DATE_FORMAT)
    4857        elif isinstance(o, datetime.time):
    4958            return o.strftime(self.TIME_FORMAT)
     59        elif decimal_available and isinstance(o, decimal.Decimal):
     60            return str(o)
    5061        else:
    51             return super(DateTimeAwareJSONEncoder, self).default(o)
     62            return super(DjangoJSONEncoder, self).default(o)
Back to Top