Serialization of custom classes.

""" Currently json dumping an object is sketchy because of the need to serialise. E.g. """ import json class Something(object): def __init__(self, arg1): self.arg1 = arg1 def __str__(self): return str(self.arg1) def __repr__(self): return str(self.arg1) def double(self): return self.arg1 * 2 test = Something(42) #json.dumps(test) """This ofc raises a TypeError as shown here ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "C:\Python26\Lib\site-packages\spyderlib\widgets\externalshell\startup.py", line 122, in runfile execfile(filename, glbs) File "C:\infobarb\test.py", line 22, in <module> json.dumps(test) File "C:\Python26\lib\json\__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "C:\Python26\lib\json\encoder.py", line 367, in encode chunks = list(self.iterencode(o)) File "C:\Python26\lib\json\encoder.py", line 317, in _iterencode for chunk in self._iterencode_default(o, markers): File "C:\Python26\lib\json\encoder.py", line 323, in _iterencode_default newobj = self.default(o) File "C:\Python26\lib\json\encoder.py", line 344, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: 42 is not JSON serializable My suggested fix and an idea used by several others could be to add a __json__ method to objects, this method would be tried by json.dumps() before it tries to serialise the argument. It should return all of the instance variables in a json format and any other infomation considered to be correct for the dump. This could be extended to provide a __json__ and a __jsons__ format where the latter returns a string format of the __json__ serialzation an example of which (crudely constructed ofc) is below. But for now I consider __json__ to return a string serialized for json dumping. """ import json def customjsondumps(obj): try: return json.dumps(obj.__json__()) except AttributeError: raise AttributeError('Object has no __json__ method.') """There are ofc several ideas for the __json__ method e.g.""" def __json__(self): """This method returns a serialized string for json.dumps""" return self.__dict__ """Or returning some fancy constructed dict, list or other serialised form for dumping into json.""" class Something(object): def __init__(self, arg1): self.arg1 = arg1 def __str__(self): return str(self.arg1) def __repr__(self): return str(self.arg1) def double(self): return self.arg1 * 2 def __json__(self): ret = self.__dict__.copy() for key, item in ret.iteritems(): ret[key] = item.__repr__() return ret test = Something(41)

On 2011-03-30, at 12:42 , Jakob Bowyer wrote:
My suggested fix and an idea used by several others could be to add a __json__ method to objects, this method would be tried by json.dumps() before it tries to serialise the argument. It should return all of the instance variables in a json format and any other infomation considered to be correct for the dump. This could be extended to provide a __json__ and a __jsons__ format where the latter returns a string format of the __json__ serialzation an example of which (crudely constructed ofc) is below. But for now I consider __json__ to return a string serialized for json dumping.
The documented method for serializing non-literal types (such as custom types) is to simply provide subclasses of ``JSONEncoder`` overriding the method ``default``. Why not just do that? Hell, you could even implement your serialization scheme through this, no need for "customjsondumps".
participants (2)
-
Jakob Bowyer
-
Masklinn