Reputation: 18929
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.
Upvotes: 11
Views: 9426
Reputation: 599778
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)
Upvotes: 24
Reputation: 991
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)
Upvotes: 1