Skip to content Skip to sidebar Skip to footer

Decimal To Json

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 serial

Solution 1:

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>>>classDecimalEncoder(json.JSONEncoder):...defdefault(self, obj):...ifisinstance(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.

Solution 2:

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

i can tell you tree think :

you can find more detail in the first link.

Solution 3:

Decimal can be cast to a float which javascript knows how to deal with

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

Solution 4:

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.

Post a Comment for "Decimal To Json"