title: Embedding JSON objects in script tags
body: <p>EDIT: For future reference, I'm using non-xhtml content type definition <code>&lt;!html&gt;</code></p>
  
  <p>I'm creating a website using Django, and I'm trying to embed arbitrary json data in my pages to be used by client-side javascript code.</p>
  
  <p>Let's say my json object is <code>{"foo": "&lt;/script&gt;"}</code>. If I embed this directly,</p>
  
  <pre><code>&lt;script type='text/javascript'&gt;JSON={"foo": "&lt;/script&gt;"};&lt;/script&gt;
  </code></pre>
  
  <p>The first  closes the json object. (also, it will make the site vulnerable to XSS, since this json object will be dynamically generated).</p>
  
  <p>If I use django's HTML escape function, the resulting output is:</p>
  
  <pre><code>&lt;script type='text/javascript'&gt;JSON={&amp;quot;foo&amp;quot;: &amp;quot;&amp;lt;/script&amp;gt;&amp;quot;};&lt;/script&gt; 
  </code></pre>
  
  <p>and the browser cannot interpret the <code>&lt;script&gt;</code> tag.</p>
  
  <p>The question I have here is,</p>
  
  <ol>
  <li>Which characters am i suppose to escape / not escape in this situation?</li>
  <li>Is there automated way to perform this in Python / django?</li>
  </ol>