[issue27362] json.dumps to check for obj.__json__ before raising TypeError

Daniel Ward report at bugs.python.org
Tue Jun 21 09:32:49 EDT 2016


Daniel Ward added the comment:

Sure, so for example:


=========
import json


class ObjectCounter:

    def __init__(self, name, count):
        self.name = name
        self.count = count

    def __json__(self):
       return '[{name}] {count}'.format(name=self.name, count=self.count)


object_counter = ObjectCounter('DC1', 3789)
my_json_string = json.dumps({'success': True, 'counter': object_counter})

============

In the above example, the value stored in my_json_string would be:

'{"success": true, "counter": "[DC1] 3789"}'

This is an untested and quick example, but I hope it explains what I'm aiming to achieve. Without the __json__ method, the json.dumps call would raise an exception along the lines of the below message, unless we create a new JSONEncoder object and call json.dumps(..., cls=MyJSONEncoder), which becomes difficult to manage and follow on larger projects.

TypeError: <ObjectCounter instance at XXX> is not JSON serializable

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue27362>
_______________________________________


More information about the Python-bugs-list mailing list