-1

I have this problem where I need to unescape the json string. To have & instead of &amp ;

From python dictionary I do this; where record_prev is a python dictionary

record_prev = self.stringify(app)
record_prev = record_prev.decode('string_escape')
response    = make_response(
    record_prev,
    200
)
response.mimetype = "application/json"

Stringify function:

def stringify(self, app=None):
    record_prev = copy.deepcopy( self.response )
    if app != None:
        app.logger.debug( record_prev["message_data"] )
    return json.dumps( record_prev )
#end def

Im having an issue on record_prev = record_prev.decode('string_escape')

It throws

AttributeError: 'str' object has no attribute 'decode'
davidism
  • 110,080
  • 24
  • 357
  • 317

1 Answers1

0

I think the html escaped characters are already inside the dictionary. For this reason I have this suggestion and use werkzeug.utils.unescape and flask.jsonify.

from flask import jsonify
from werkzeug.utils import unescape

def deep_unescape(data):
    if isinstance(data, str):
        return unescape(data)
    elif isinstance(data, (tuple, list)):
        return [deep_unescape(e) for e in data]
    elif isinstance(data, dict):
        return {deep_unescape(k):deep_unescape(v) for k,v in data.items()}
    else: 
        return data

data = {
    'key0&val': '<v0>', 
    'key1&val': ['<v1.1>', '<v1.2>'], 
    'key2&val': {
        'k0&v0': '<v0>', 
        'k1&v1': '<v1>', 
    }, 
    'intval': 102, 
    'floatval': 1.2344
}

response = jsonify(deep_unescape(data))
Detlef
  • 3,380
  • 2
  • 4
  • 21