Decimal value for JSON

I am pulling the amount from the database, which is a decimal value. I am trying to use this value as a result of JSON

json.dumps( { 'sum': amount } ) #where amount is my Decimal 

Django cannot serialize Decimal . I can convert it to a string, but I need a digital type in JSON. If I try to convert it to float , I get more than two decimal places.

What should happen if possible to get a result similar to the following?

 { 'sum': 500.50 } 
+7
python django
source share
4 answers

What you can do is extend the JSONDecoder class to provide a custom decimal type serializer, similar to the example in this document: http://docs.python.org/py3k/library/json.html

 >>> import json >>> class DecimalEncoder(json.JSONEncoder): ... def default(self, obj): ... if isinstance(obj, Decimal): ... return "%.2f" % obj ... return json.JSONEncoder.default(self, obj) ... 

This is a non-working example of how to do this, hopefully a good starting point for you.

+11
source share

From this link: http://code.google.com/p/simplejson/issues/detail?id=34 .

I can tell you what the tree thinks:

You can find more information in the first link.

0
source share

There is no such thing as a decimal type in Javascript, nor among standard types in python. This is a database type, not part of JSON. Take a float or do integer arithmetic.

0
source share

A decimal can be cast for a float that javascript knows how to handle

 json.dumps( { 'sum': float(amount) } ) 
0
source share

All Articles