'''
Created on May 15, 2017

@author: Bart
'''

import json

class Serializable:
    
    def serialize(self):
        """ does not take into account cyclic links, and only works with attribute types basic, list and Serializable """
        attrs = vars(self)
        for attr_name in attrs.keys():
            attr_val = attrs[attr_name]
            try:
                json.dumps(attr_val)
            except TypeError:
                if isinstance(attr_val, list):
                    attrs[attr_name] = [item.serialize() for item in attr_val]
                else:
                    attrs[attr_name] = attr_val.serialize()
        return attrs
    
    def to_json(self):
        return json.dumps(self.serialize())