"Decimal not JSON serializable"?

718 views
Skip to first unread message

JHeasly

unread,
Dec 18, 2006, 5:45:10 PM12/18/06
to Django users
Hello all,

I'm following the "Serializing Django objects" documentation and have a
view pretty much verbatim from the docs:

def my_json_view(request):
data = serializers.serialize("json", Location.objects.all())
return HttpResponse(data, mimetype='text/javascript')

My Location model includes decimal latitude and longitude data. When I
test the above view using the Django shell, it works, but when I try it
via a browser request, I get this:

Decimal("44.048708") is not JSON serializable
Request Method: GET
Request URL: http://www.my_url.com/maps/json/
Exception Type: TypeError
Exception Value: Decimal("44.048708") is not JSON serializable
Exception Location: ... [snip] ...
/django/utils/simplejson/encoder.py in default, line 258

Also, the above will works via the browser when I specify "xml" as the
serialization format. The "json" format just doesn't like my decimals.
What am I doing wrong?

Thanks for any guidance,
John

DavidA

unread,
Dec 18, 2006, 11:33:00 PM12/18/06
to Django users

Its just a case that isn't handled in
django.utils.simplejson.encoder.py. I'm not really sure the "right" way
to implement it but you could just change line 176 in _iterencode()
from:

176 elif isinstance(key, float):
177 key = floatstr(key, allow_nan)

to

176 elif isinstance(key, float) or isinstance(key,
decimal.Decimal):
177 key = floatstr(key, allow_nan)

But I also think JSONEncoder is meant to be subclassed for these types
of cases. I was just surprised to see that things like Decimal and date
weren't handled since these are so common as return types from the
DB-API.

John Lenton

unread,
Dec 19, 2006, 8:32:12 AM12/19/06
to django...@googlegroups.com
On 12/19/06, DavidA <david.av...@gmail.com> wrote:
>
>
> 176 elif isinstance(key, float) or isinstance(key,
> decimal.Decimal):
> 177 key = floatstr(key, allow_nan)

isinstance can take an iterable of classes as its second argument, so
that you could write that as isinstance(key, (float, decimal.Decimal))

--
John Lenton (jle...@gmail.com) -- Random fortune:
The trouble with a lot of self-made men is that they worship their creator.

Reply all
Reply to author
Forward
0 new messages