I've got this function which returns an SQLObject instance as a dict (taking into account inherited classes, properties, etc). It doesn't work right now on SQLObject classes which inherit from another class but add new attributes, so that's a work in progress, but I feel like this could be done smarter/better in Python.
What do you think?
PS the purpose of this is to allow a generic presentation of an object as a JSON document. It returns a dict which can be then given to json.dumps. If you've got a different way to convert an SQLObject to a JSON doc, that would be cool as well
def sqlobject_to_dict(obj):
obj_dict = {}
cls_name = type(obj)
has_props = False
for attr in vars(cls_name):
attr_parent = type(getattr(obj, attr)).__bases__[0]
if isinstance(getattr(cls_name, attr), property):
has_props = True
if isinstance(getattr(obj, attr), Decimal):
obj_dict[attr] = float(getattr(obj, attr))
elif isinstance(getattr(obj, attr), list):
dict_list = []
for list_item in getattr(obj, attr):
dict_list.append(sqlobject_to_dict(list_item))
obj_dict[attr] = dict_list
elif isinstance(getattr(obj, attr), dict):
dict_dict = {}
for key, val in getattr(obj, attr):
dict_dict[key] = sqlobject_to_dict(val)
obj_dict[attr] = dict_dict
elif attr_parent == SQLObject:
obj_dict[attr] = sqlobject_to_dict(getattr(obj, attr))
else:
obj_dict[attr] = getattr(obj, attr)
elif not has_props and attr_parent != SQLObject:
if "_get_" in attr:
attr_name = '_'.join(attr.split('_', 3)[3:])
if hasattr(obj, attr_name):
obj_dict[attr_name] = getattr(obj, attr_name)
return obj_dict