title: character escaping: from Python string literal to JSON and then to HTML
body: <p>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.</p>
  
  <p>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:</p>
  
  <ol>
  <li>Serialize the Python string literal into JSON and escape the characters as required by JSON.</li>
  <li>Once the JSON object is received at the client-end, escape the characters as required by HTML. Note that I use jQuery.</li>
  </ol>
  
  <p>Is my view of the above two stages correct? If so, how can I achieve them?</p>
  
  <p>If it's easier for you to explain with an example. Here is one: </p>
  
  <pre><code>s = '&lt;a href="http://www.foo.com/bar/"&gt;"Click Here&amp;Here"&lt;/a&gt;'
  </code></pre>
  
  <p>where <code>s</code> is a Python string literal. And I want to see it become</p>
  
  <pre><code>&lt;a href="http://www.foo.com/bar/"&gt;"Click Here&amp;amp;Here"&lt;/a&gt;
  </code></pre>
  
  <p>in the HTML. </p>