This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Daniel Ward
Recipients Daniel Ward, abarry
Date 2016-06-21.13:32:49
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
Sure, so for example:

import json

class ObjectCounter:

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

    def __json__(self):
       return '[{name}] {count}'.format(, 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
Date User Action Args
2016-06-21 13:32:49Daniel Wardsetrecipients: + Daniel Ward, abarry
2016-06-21 13:32:49Daniel Wardsetmessageid: <>
2016-06-21 13:32:49Daniel Wardlinkissue27362 messages
2016-06-21 13:32:49Daniel Wardcreate