I need a convenient way to unescape HTML characters within string fields when sending out JSON. I thought writing a custom json.JSONEncoder
would do the trick. My encoder looks like so:
import jinja2, json
class EscapingJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, basestring):
obj = jinja2.Markup(obj).unescape()
return json.JSONEncoder.default(self, obj)
I placed a debug statement within default
but it never appeared so I'm assuming that the encoder handles the string encoding before it reaches my custom default
implementation.
How can I achieve this?
You should override the encode method since 'default' is not called for string datatypes
class EscapingJSONEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, basestring):
obj = jinja2.Markup(obj).unescape()
return json.JSONEncoder.encode(self, obj)