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
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.
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