Serializing Objects of depth `N`

Many of the programmers might have faced the problem of serializing objects of depth `N` or serializing nested objects. Personally i have also faced such a situation and here is the solution which i found. There may be better implementations of serializing nested objects, but i think this might be helpful for some novices like me.

#! /usr/bin/python
import json

class Reference(object):

class Engineering(Reference):
   subject = 'ECE'
   college = 'Jyothi Engineering College'

   _serializable_fields = ['subject', 'college']

class Programmer(Reference):
   designation = 'Software Engineer'
   company = 'Scintilla Technologies'

   _serializable_fields = ['designation', 'company']

class Individual(object):
   name = 'Akhil Lawrence'
   age = 23
   job = Programmer()
   education = Engineering()

   _serializable_fields = ['name', 'age', 'job', 'education']

def Serialize(obj, excludes=[]):
   response = dict()
   for attr_name in obj._serializable_fields:
       if attr_name in excludes:
           attr = getattr(obj, attr_name)
           if attr and not isinstance(attr, Reference):
               response.update({attr_name: attr})
           elif attr and isinstance(attr, Reference):
               response.update({attr_name: Serialize(attr)})
   return response

def Serializer(objs, excludes=[]):
   response = []
   for obj in objs:
       response.append(Serialize(obj, excludes))
   return response

if __name__ == '__main__':
   objs = [Individual(), Individual()]
   excludes = []
   print json.dumps(Serializer(objs, excludes), indent=4)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s