Skip to content

Instantly share code, notes, and snippets.

@srkama
Created December 24, 2015 05:12
Show Gist options
  • Select an option

  • Save srkama/d49f960091aac088029d to your computer and use it in GitHub Desktop.

Select an option

Save srkama/d49f960091aac088029d to your computer and use it in GitHub Desktop.
import json
def object_to_dict(obj):
"""
Method to get dict of object properties. This method identified object properties and returns
a dict of properties with key, value as property name and property value respectively
:param : object
:return: obj_dict : dict
"""
obj_dict = {}
print vars(obj.__class__)
for name, value in vars(obj.__class__).items():
if isinstance(value, property):
obj_dict[name] = getattr(obj, name)
return obj_dict
def json_repr(obj):
"""Represent instance of a class as JSON.
Arguments:
obj -- any object
Return:
String that represent JSON-encoded object.
"""
def serialize(obj):
"""Recursively walk object's hierarchy."""
if isinstance(obj, (bool, int, long, float, basestring)):
return obj
elif isinstance(obj, dict):
obj = obj.copy()
for key in obj:
obj[key] = serialize(obj[key])
return obj
elif isinstance(obj, list):
return [serialize(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(serialize([item for item in obj]))
elif hasattr(obj, '__dict__'):
print type(obj), "this is check point"
return serialize(object_to_dict(obj))
else:
return repr(obj) # Don't know how to handle, convert to string
return json.dumps(serialize(obj))
class A(object):
def __init__(self, a=None, b=None):
self.a = 5
self.b = 5
@property
def a(self):
return self._a
@a.setter
def a(self, value):
self._a = value
@property
def b(self):
return self._b
@b.setter
def b(self, value):
self._b = value
def __str__(self):
return str(self.__dict__)
class B(object):
def __init__(self, lista):
self.lista = lista
@property
def lista(self):
return self._lista
@lista.setter
def lista(self, value):
self._lista = value
def __str__(self):
return str(self.__dict__)
def to_json(self):
print self
return json_repr(self)
if __name__ == "__main__":
a = A()
b = B([a]*5)
print a.__dict__
print b
print json.loads(b.to_json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment