How to unescape HTML characters when encoding JSON with Python

Go To StackoverFlow.com

0

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?

2012-04-04 20:13
by Matt W
how are you using this class - aschmid00 2012-04-04 20:44


0

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)
2012-04-04 22:13
by Maksym Polshcha
Ads