简体   繁体   中英

character escaping: from Python string literal to JSON and then to HTML

I have designed a JSON object that is used as the format of AJAX response sending back to the clients of my web app. I am in the process of enhancing it by putting html code into it. But the character escaping required is making me rather uncomfortable due to my lack of precise knowledge and experience on the topic.

I use Python/Django as my server-end language/framework. To get from a Python string literal to a proper HTML node for browsers to consume, with my vague knowledge on character escaping, I guess I would need two stages of character escaping:

  1. Serialize the Python string literal into JSON and escape the characters as required by JSON.
  2. Once the JSON object is received at the client-end, escape the characters as required by HTML. Note that I use jQuery.

Is my view of the above two stages correct? If so, how can I achieve them?

If it's easier for you to explain with an example. Here is one:

s = '<a href="http://www.foo.com/bar/">"Click Here&Here"</a>'

where s is a Python string literal. And I want to see it become

<a href="http://www.foo.com/bar/">"Click Here&amp;Here"</a>

in the HTML.

Do you need to escape it client side? You can do it in Python before encoding it to JSON:

from cgi import escape
from json import dumps

ajax_response = dumps(escape('<a href="http://www.example.com/path/location'
                             '?query=string&more=this#anchor">'
                             'FooBar & Friends</a>'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM