To avoid code repetition, as in Fred Laurent, I overloaded the __iter__() method as follows. It also allows you to "jsonize" the list, datetime and decimal elements without any additional dependencies, just use dict ().
import datetime import decimal class Jsonable(object): def __iter__(self): for attr, value in self.__dict__.iteritems(): if isinstance(value, datetime.datetime): iso = value.isoformat() yield attr, iso elif isinstance(value, decimal.Decimal): yield attr, str(value) elif(hasattr(value, '__iter__')): if(hasattr(value, 'pop')): a = [] for subval in value: if(hasattr(subval, '__iter__')): a.append(dict(subval)) else: a.append(subval) yield attr, a else: yield attr, dict(value) else: yield attr, value class Identity(Jsonable): def __init__(self): self.name="abc name" self.first="abc first" self.addr=Addr() class Addr(Jsonable): def __init__(self): self.street="sesame street" self.zip="13000" class Doc(Jsonable): def __init__(self): self.identity=Identity() self.data="all data" def main(): doc=Doc() print "-Dictionary- \n" print dict(doc) print "\n-JSON- \n" print json.dumps(dict(doc), sort_keys=True, indent=4) if __name__ == '__main__': main()
Exit:
-Dictionary- {'data': 'all data', 'identity': {'first': 'abc first', 'addr': {'street': 'sesame street', 'zip': '13000'}, 'name': 'abc name'}} -JSON- { "data": "all data", "identity": { "addr": { "street": "sesame street", "zip": "13000" }, "first": "abc first", "name": "abc name" } }
Hope this helps! Thanks
JeanPaulDepraz Jan 31 '15 at 16:11 2015-01-31 16:11
source share