In my web application I often need to serialize objects as JSON.
Not all objects are JSON-serializable by default so I am using my own encode_complex method which is passed to the simplejson.dumps as follows: simplejson.dumps(context, default=self.encode_complex)
Is it okay to define my own magic method called __json__(self) and then use code similar to the following in encode_complex method?
def encode_complex(self, obj):
# additional code
# encode using __json__ method
try:
return obj.__json__()
except AttributeError:
pass
# additional code
The
__double_underscore__names are reserved for future extensions of the Python language and should not be used for your own code (except for the ones already defined, of course). Why not simply call the methodjson()?Here is the relevant section from the Python language reference: