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 method json()
?
Here is the relevant section from the Python language reference:
__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of__*__
names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
You probably don't want to use double underscore due to name mangling http://docs.python.org/reference/expressions.html#atom-identifiers -- However in concept what you're doing is fine for your own code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With