title: How to escape json strings in freemarker
body: <p>We are building a restful api using Spring MVC and freemarker as the templating language. We have chosen to build json responses in the freemarker</p>
  
  <p>Example freemarker.ftl:</p>
  
  <pre><code>{
  "field1" : "${response.value1}",
  "field2" : "${response.value2}"
  }
  </code></pre>
  
  <p>We get a problem when the strings in the values contain quotation marks (or any of the other characters in the JSON syntax).</p>
  
  <p>The question: <strong>How can I escape these strings using freemarker?</strong></p>
  
  <p>We have looked at <code>?xml</code> or <code>?html</code> but they do not cover all relevant characters (such as <code>\</code>). </p>
  
  <p><strong>EDIT:</strong> <code>?js_string</code> will escape the string to comform with JavaScript. And since JSON is based on JavaScript (JavaScript Object Notation), it will work.</p>
  
  <p><strong>EDIT2:</strong> In case a single-quote pops up, <code>?js_string</code> will escape it which again leads to invalid JSON. The hotfix for it is:</p>
  
  <pre><code>${variable?js_string?replace("\\'", "\'")} 
  </code></pre>
  
  <p>and if you really want to be picky:</p>
  
  <pre><code>${variable?js_string?replace("\\'", "\'")?replace("\\&gt;","&gt;")}
  </code></pre>
  
  <p>Alternatively if you use Spring: <a href="http://www.springsurf.org/sites/1.0.0.M3/spring-webscripts/spring-webscripts-documentation/reference/html-single/index.html#js-api-index-org.springframework.extensions.webscripts.json.jsonutils" rel="nofollow noreferrer">http://www.springsurf.org/sites/1.0.0.M3/spring-webscripts/spring-webscripts-documentation/reference/html-single/index.html#js-api-index-org.springframework.extensions.webscripts.json.jsonutils</a></p>