Serialize python parent class from inherited class to JSON - possible or stupid? -


i know there lot of question on json serialization, i'm still not grasping seems.

given following class:

import json  class basemongoobject(object):     def __init__(self):         pass      def jsonify(self):         return json.dumps(self, default=lambda o: o.__dict) 

and following derived class:

from assetfacts import assetfacts bmo import basemongoobject  class asset(basemongoobject):     def __init__(self):         basemongoobject.__init__(self)         self.facts = assetfacts()         self.serial = none 

trying call asset.jsonify() using following piece of test code:

from asset import asset  def test_me():     = asset()     a.serial = '123asdf'      print a.jsonify()   if __name__ == '__main__':     test_me() 

produces following:

    traceback (most recent call last):   file "../bin/test.py", line 17, in <module>     test_me()   file "../bin/test.py", line 13, in test_me     print a.jsonify()   file "/users/vlazarenko/mp/ac/lib/bmo.py", line 8, in jsonify     return json.dumps(self, default=lambda o: o.__dict)   file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps     sort_keys=sort_keys, **kw).encode(obj)   file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode     chunks = self.iterencode(o, _one_shot=true)   file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode     return _iterencode(o, 0)   file "/users/vlazarenko/mp/ac/lib/bmo.py", line 8, in <lambda>     return json.dumps(self, default=lambda o: o.__dict) attributeerror: 'asset' object has no attribute '_basemongoobject__dict' 

where going braindead this? ideally wouldn't wanna bothered amount of levels of inheritance, serialize way top.

you want jsonify self.__dict__ instead:

def jsonify(self):     return json.dumps(self, default=lambda o: o.__dict__) 

names start double underscore mangled protect them accidental overriding in subclass, .__dict rewritten ._basemongoobject__dict.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -