I have a special object that can contain a literal json string, which I intend to use as a field in a larger JSON object, as the literal value itself (and not a string containing JSON).
I want to write my own encoder that can do this, i.e.
> encoder.encode({ > 'a': LiteralJson('{}') > }) {"a": {}}
I donβt think that subclassing JSONEncoder and overriding by default will work, because at best I can return a string that will produce the result {"a": "{}"} .
Encoding overrides also do not work when LiteralJson is nested somewhere inside another dictionary.
The background for this, if you're interested, is that I store JSON-encoded values ββin the cache, and it seems to me that this is a waste for deserialization, and then reinitialization. It works that way, but some of these values ββare quite long, and it just seems like a huge waste.
The following encoder will do what I like (but it 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)
json python
Kevin dolan
source share