Welcome, guest | Sign In | My Account | Store | Cart

The json.dumps need to be feed with some class (cls =someClass) but what if we want to change the class dynamically? This example can be done by declaring the listOfClasses in class level of course, but the idea is to be changeable. This can be done by the class factory function encoderFacory

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    import json

    class smallDuck(object):
        def __init__(self, one, two, tree):
            self.one = one
            self.two = two
            self.tree = tree

    class myEncoder(json.JSONEncoder):

        def isInClasses(self, obj):
            for i in self.listOfClasses :
                if isinstance(obj, i):
                    return True
            return False

        def default(self, obj):
            if isinstance(obj, smallDuck):
                return { obj.__class__.__name__ : obj.__dict__ }
            return json.JSONEncoder.default(self, obj)

    def encoderFactory(listOfClasses):
        classDict = {"listOfClasses" : listOfClasses }
        return type("newEncoder", (myEncoder, ) , classDict)

    duck = [smallDuck("shit", 1, smallDuck(1,2,3)),2,3,4]
    with open("try.json", "w") as myf:
        string = json.dumps(duck, cls = encoderFactory([smallDuck]))
        myf.write(string)