I am developing a “desktop” application running on “browser” using “django”. When
I need json response, I use django’s JsonResponse class. JsonResponse encode a dictionary
into json format and it handle datetime and decimal types. The problem is JsonResponse
encodes decimal to strings. I found some posts said this issue began after django stoped
using simplejson. What makes django translate decimals into strings? What if I
want numbers, not strings in json? I finally managed to solve it in a not-that-smart
way and here it is.
How does django’s JsonResponse encode dictionaries?
JsonResponse use python’s json library and DjangoJSONEncoder (default).
What DjangoJSONEncoder does is checking the variables which can not be encoded into
json by python’s json library. Its’ “default” method is a fallback. In my case, it
changes a decimal to a string.
In python’s json encoder, _iterencode do not encode decimal so it ask the default
function to change it into another iteratable type, then encode it again (recursively).
DjangoJSONEncoder’s default then give it a string and the decimals finally become strings.
The first solution I found in stackoverflow is making a new class which inherit from DjangoJSONEncoder and return decimal’s float version. This works if I do not need the fixed point number.
Final solution: simplejson
Install simplejson (easy_install simplejson). Then write a new encoder (modified
version of django’s). Now the simplejson take care of decimals while I can still
encode the other objects (for example, datetime) in prefered formats if I need to.