decimal is not json serializable.

818 views
Skip to first unread message

Meenu

unread,
Jan 14, 2010, 2:50:06 AM1/14/10
to Django users
Hello all,

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

if xhr:
return HttpResponse(simplejson.dumps(form_data),
mimetype='application/javascript')

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

Any help will be appreciated.

Thanks

Shawn Milochik

unread,
Jan 14, 2010, 9:56:07 AM1/14/10
to django...@googlegroups.com
You could always convert decimals to strings. There's probably a better solution out there, but this should at least be a quick-fix.

Shawn

Simon Brunning

unread,
Jan 14, 2010, 10:31:19 AM1/14/10
to django-users
2010/1/14 Meenu <meenaksh...@gmail.com>:

You can override the JSON encoder's behaviour, something like (untested):

class MyJsonEncoder(simplejson.JSONEncoder):
"""JSON encoder which understands decimals."""

def default(self, obj):
'''Convert object to JSON encodable type.'''
if isinstance(obj, decimal.Decimal):
return "%s" % obj

return super(MyJsonEncoder, self).default(self, obj)

The simplejson.dumps() method takes an optional cls keyword argument -
that's where you plug MyJsonEncoder in.

--
Cheers,
Simon B.

Jani Tiainen

unread,
Jan 14, 2010, 1:46:02 PM1/14/10
to django...@googlegroups.com

I just recently wrote blog entry about JSON-RPC which contais my own
version of augmented JSON encoder
<http://drpinkpony.wordpress.com/2010/01/12/django-json-rpc-service/>.

--

Jani Tiainen

Reply all
Reply to author
Forward
0 new messages