simplejson: alternate encoder not called enought

P

Pierre Hanser

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?
thanks in advance
 
C

Chris Rebert

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top