title: What is the correct way to encode an inline javascript object, in order to protect it from XSS?
body: <p>It turns out the following which looks like valid javascript, is not: </p>
  
  <pre><code>&lt;html&gt; 
  &lt;body&gt;
  &lt;script&gt;
   json = {test: "&lt;/script&gt;&lt;script&gt;alert('hello');&lt;/script&gt;"};
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The same text, when returned JSON via an ajax api works just as expected. However when rendered in-line results in a basic XSS issues. </p>
  
  <p>Given an arbitrary correct JSON string, what do I need to do server side to make it safe for in-line rendering? </p>
  
  <p><strong>EDIT</strong>
  Ideally I would like the fix to work with the following string as well: </p>
  
  <p><code>json = {test: "&lt;\/script&gt;&lt;script&gt;alert('hello');&lt;\/script&gt;"};</code></p>
  
  <p>Meaning, I have no idea how my underlying library is encoding the <code>/</code> char, it may have chosen to encode it, or it may have not. (so its likely a regex fix is more robust) </p>