Author Daniel Ward
Recipients Daniel Ward, abarry
Date 2016-06-21.13:32:49
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1466515969.96.0.483864181864.issue27362@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2016-06-21 13:32:49Daniel Wardsetrecipients: + Daniel Ward, abarry
2016-06-21 13:32:49Daniel Wardsetmessageid: <1466515969.96.0.483864181864.issue27362@psf.upfronthosting.co.za>
2016-06-21 13:32:49Daniel Wardlinkissue27362 messages
2016-06-21 13:32:49Daniel Wardcreate