tags:

views:

77

answers:

5
+3  Q: 

Decimal to JSON

To keep it short & sweet:

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 js 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? { 'sum': 500.50 }

ty

+1  A: 

look over this question: http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module

It seems its similar query you have !!!

Tumbleweed
Thanks for the link :)
Justin
+5  A: 

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.

Jerub
Thanks, I like this solution the best so far :)
Justin
Actually Django provides a built-in class for exactly this - `django.core.serializers.json.DjangoJSONEncoder` - which you can use directly by doing `simplejson.dumps(mydict, class=DjangoJSONEncoder)`. It also deals with datetimes.
Daniel Roseman
@Daniel Thanks. 'class=DjangoJSONEncoder' needed to be 'cls=DjangoJSONEncoder'. This does work, but it gives me a string value :(
Justin
hehe this gives me just a string value the same as just doing 'str(amount)' in the json.dumps calls... I've decided to just leave it as a string and handle it on the client..
Justin
You can make it whatever you want, just change the `return "%.2f" % obj` line.
Jerub
A: 

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.

singularity
+1  A: 

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.

knitti
Yes, I know there is no matching type in JavaScript, my values will never be that large. I simply want them to come down in a regular monetary format "5.95", but not in string format.
Justin
A: 

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


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




mossplix
In my question I noted that I didn't want to pass down a float due to them having a large number of decimal places.
Justin