simplejson: alternate encoder not called enought
Chris Rebert
clp2 at rebertia.com
Sun Mar 22 05:16:07 EDT 2009
On Sat, Mar 21, 2009 at 2:11 PM, Pierre Hanser <hanser at club-internet.fr> wrote:
> hello
>
> I'm trying to use simplejson to encode some
> python objects using simplejson dumps method.
>
> The dumps method accept a cls parameter to specify
> an alternate encoder. But it seems that this alternate
> encoder is called only as a last resort, if object type
> is not int, string, and all other basic types.
>
> My problem is that i wanted to specify an encoding
> for a dbus.Boolean object which inherits from int.
>
> As int is handled by the standard encoder, the alternate
> encoder is never called and a dbus.Boolean is converted
> to 0 or 1 instead of true or false.
>
> Could someone knowledgeabled enought confirm my diagnostic?
Indeed, this does appear to be the case:
import json
class Foo(int):
def __init__(self, val):
int.__init__(self, val)
self.val = val
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return ["foo", obj.val]
return json.JSONEncoder.default(self, obj)
print "Expect:", json.dumps(["foo", 42])
print "Got: ", json.dumps(Foo(42), cls=MyEncoder)
#output:
# Expect: ["foo", 42]
# Got: 42
The docs are not entirely clear as to whether this should be expected or not.
I'd file a bug. If this behavior is deemed correct, then at the least
the docs should be clarified to indicate that the default encodings
apply to certain builtin types *and their subclasses*.
Cheers,
Chris
--
I have a blog:
http://blog.rebertia.com
More information about the Python-list
mailing list