serializable.py 748 B

1234567891011121314151617181920212223242526
  1. '''
  2. Created on May 15, 2017
  3. @author: Bart
  4. '''
  5. import json
  6. class Serializable:
  7. def serialize(self):
  8. """ does not take into account cyclic links, and only works with attribute types basic, list and Serializable """
  9. attrs = vars(self)
  10. for attr_name in attrs.keys():
  11. attr_val = attrs[attr_name]
  12. try:
  13. json.dumps(attr_val)
  14. except TypeError:
  15. if isinstance(attr_val, list):
  16. attrs[attr_name] = [item.serialize() for item in attr_val]
  17. else:
  18. attrs[attr_name] = attr_val.serialize()
  19. return attrs
  20. def to_json(self):
  21. return json.dumps(self.serialize())