Consider I have a special object which may hold a literal json string, that I intend to use as a field in a larger JSON object, as the literal value itself (not a string containing the JSON).
I want to write a custom encoder that can accomplish this, ie:
> encoder.encode({
> 'a': LiteralJson('{}')
> })
{"a": {}}
I don't believe subclassing JSONEncoder and overriding default will work, because at best there, I can return the string, which would make the result {"a": "{}"}
.
Overriding encode also appears not to work when the LiteralJson is nested somewhere inside another dictionary.
The background for this, if you are interested, is that I am storing JSON-encoded values in a cache, and it seems to me to be a waste to deserialize then reserialize all the time. It works that way, but some of these values are fairly long and it just seems like a huge waste.
The following encoder would accomplish what I like (but seems unnecessarily slow):
class MagicEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, LiteralJson):
return json.loads(obj.content)
else:
return json.JSONEncoder.default(self, obj)