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 <[email protected]>
<http://bugs.python.org/issue27362>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com