Re: "Decimal not JSON serializable"?

2006-12-19 Thread John Lenton

On 12/19/06, DavidA <[EMAIL PROTECTED]> wrote:
>
>
> 176   elif isinstance(key, float) or isinstance(key,
> decimal.Decimal):
> 177key = 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 ([EMAIL PROTECTED]) -- Random fortune:
The trouble with a lot of self-made men is that they worship their creator.

--~--~-~--~~~---~--~~
 You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: "Decimal not JSON serializable"?

2006-12-18 Thread DavidA


JHeasly wrote:
> 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

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):
177key = floatstr(key, allow_nan)

to

176   elif isinstance(key, float) or isinstance(key,
decimal.Decimal):
177key = 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.


--~--~-~--~~~---~--~~
 You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---