0

I know there are a lot of question on JSON serialization, but I'm still not grasping this it seems.

Given the following class:

import json

class BaseMongoObject(object):
    def __init__(self):
        pass

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

And the following derived class:

from assetfacts import AssetFacts
from bmo import BaseMongoObject

class Asset(BaseMongoObject):
    def __init__(self):
        BaseMongoObject.__init__(self)
        self.facts = AssetFacts()
        self.serial = None

Trying to call asset.jsonify() by using the following piece of test code:

from asset import Asset

def test_me():
    a = Asset()
    a.serial = '123asdf'

    print a.jsonify()


if __name__ == '__main__':
    test_me()

Produces the 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 am I going braindead about this? Ideally I wouldn't wanna be bothered with amount of levels of inheritance, just serialize all the way from the top.

favoretti
  • 29,299
  • 4
  • 48
  • 61
  • Did you write the code in the first snippet? If so, did you actually mean `self.__dict` or did you mean `self.__dict__`? –  Mar 24 '14 at 12:27
  • My my my... Please shoot me. Thank you! :) – favoretti Mar 24 '14 at 12:28
  • Add it as the answer and I'll accept it. :) Thanks again, I almost couldn't believe my eyes that this doesn't work and it was something I am overlooking for an hour already. – favoretti Mar 24 '14 at 12:29

1 Answers1

1

You want to jsonify self.__dict__ instead:

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

Names that only start with a double underscore are mangled to protect them from accidental overriding in a subclass, .__dict was rewritten to ._BaseMongoObject__dict.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yep, thanks. As pointed out in comments by @delnan it was indeed a classic typo I was overlooking stubbornly. (edit) 5 min to accept :) – favoretti Mar 24 '14 at 12:30