Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to pass Decimal objects to json

Tags:

json

django

I have a query set which contains Decimal objects. I want to pass this data to a json dump along the lines:

ql = Product.objects.values_list('length', 'width').get(id=product_id)
data = simplejson.dumps(ql)

TypeError: Decimal('62.20') is not JSON serializable

How should I pass these values to json. Of course I could cast the values to string - but I'm guessing this is not a good solution.

Any help much appreciated.

like image 422
Darwin Tech Avatar asked Nov 06 '12 18:11

Darwin Tech


2 Answers

Django already includes an encoder than can deal with decimals, as well as datetimes: django.core.serializers.json.DjangoJSONEncoder. Just pass that as the cls parameter:

data = simplejson.dumps(ql, cls=DjangoJSONEncoder)
like image 163
Daniel Roseman Avatar answered Oct 15 '22 23:10

Daniel Roseman


Here's an answer I found on this question: Python JSON serialize a Decimal object

How about subclassing json.JSONEncoder?

class DecimalEncoder(simplejson.JSONEncoder):
    def _iterencode(self, o, markers=None):
        if isinstance(o, decimal.Decimal):
            # wanted a simple yield str(o) in the next line,
            # but that would mean a yield on the line with super(...),
            # which wouldn't work (see my comment below), so...
            return (str(o) for o in [o])
        return super(DecimalEncoder, self)._iterencode(o, markers)

In your case, you would use it like this:

data = simplejson.dumps(ql, cls=DecimalEncoder)
like image 41
Amit Avatar answered Oct 15 '22 22:10

Amit