Python serializable objects json [duplicate]

Write your own encoder and decoder, which can be very simple like return __dict__

e.g. here is a encoder to dump totally recursive tree structure, you can enhance it or use as it is for your own purpose

import json

class Tree(object):
    def __init__(self, name, childTrees=None): = name
        if childTrees is None:
            childTrees = []
        self.childTrees = childTrees

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if not isinstance(obj, Tree):
            return super(MyEncoder, self).default(obj)

        return obj.__dict__

c1 = Tree("c1")
c2 = Tree("c2") 
t = Tree("t",[c1,c2])

print json.dumps(t, cls=MyEncoder)

it prints

{"childTrees": [{"childTrees": [], "name": "c1"}, {"childTrees": [], "name": "c2"}], "name": "t"}

you can similarly write a decoder but there you will somehow need to identify is it is your object or not, so may be you can put a type too if needed.

Leave a Comment