Q:

JSONEncoder subclass to return actual JSON representation, not serializable object

I'm trying to encode instances of a custom python class ISOWeek using python 2.7's builtin json module. I want it to be encoded not to a JS string (such as "2012-08"), but to a constructor call: new ISOWeek({year: 2012, kw: 8}). Python's json docs say I should sublass JSONEncoder and override the default method, however I can only return another JSON serializable object from it, not the actual serialization. Looking at the json.py source, I don't see an obvious way to hack the module. Any suggestions?

A:

Instead of putting a constructor call directly into the JSON (which makes it invalid JSON), I would recommend formatting your data so that you know what is going on, and just modify the JS to do the correct conversion, for example instead of the following:
{"date": new ISOWeek({year: 2012, kw: 8})}

I would suggest something like this:
{"date": ["ISOWeek", {"year": 2012, "kw": 8}]}

