Decimal to JSON [duplicate]
I'm pulling a sum from a DB which is a decimal value. I'm trying to use that value in a JSON result
json.dumps( { 'sum': amount } ) #where amount is my Decimal
Django can't serialize the Decimal
.
I can convert it to a string, but I'd like a numeric type within the JSON.
If I try and convert it to a float
I end up with more than 2 decimal places.
What needs to happen, if possible, to get a result like the following?
{ 'sum': 500.50 }
What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, 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)
...
That's a nonworking example of how to do it, hopefully a good starting point for you.
From this link : http://code.google.com/p/simplejson/issues/detail?id=34.
i can tell you tree think :
use cjson it work fine with decimal values.
use monkey patching like the example from this link: http://code.google.com/p/simplejson/issues/detail?id=61
use jsonutil see the last comment : http://code.google.com/p/simplejson/issues/detail?id=34#c28
you can find more detail in the first link.
Decimal can be cast to a float which javascript knows how to deal with
json.dumps( { 'sum': float(amount) } )
There's no such thing as a Decimal type in Javascript, and also among the standard types in python. It is a database-spcific type and not part of JSON. Take Float or do an integer arithmetic.
精彩评论