mardi 4 août 2015

python custom JSON encoder/decoder not working as expected

I am trying to encode/decode nested objects and I have the list of nested objects as a string instead of JSON objects.

class A:
    def __init__ (self, n, a):
        self.n = n
        self.a = a

class B:
    def __init__ (self, b, listOfA):
        self.b = b
        self.listOfA = []
        for a in listOfA:
            self.listOfA.append(a)

class AEncoder:
    def default (self, obj):
        if isinstance (obj, A):
            return {
                'n' : obj.n
                'a' : obj.a
            }
        return json.JSONEncoder.default(self, obj)

class BEncoder:
    def default (self, obj):
        if isinstance (obj, B):
            return {
                'b' : obj.n
                'listOfA' : json.dumps(obj.listOfA, cls=AEncoder)
            }
        return json.JSONEncoder.default(self, obj)

listOfA = [A('n1', 'a1'), A('n2', 'a2')]
tmpB = B('b', listOfA)

For object A it is working correctly as it is fairly straight forward. The output for B I get is something like this:

{
    "b" : "b"
    "listOfA" : "[{\"n\" : \"n1\", \"a\" : \"a1\"}, {\"n\" : \"n2\", \"a\" : \"a2\"}]"
}

Any ideas where I am wrong? The output should be like this:

{
    "b" : "b"
    "listOfA" : [{"n" : "n1", "a" : "a1"}, {"n" : "n2", "a" : "a2"}]
}

Aucun commentaire:

Enregistrer un commentaire