JSON escaping in Freemarker

XML knows the concept of CDATA, a container where non-interpreted/’binary’ information can be stored. JSON also has its list of non-allowed characters that will break the JSON format. One can ‘manually’  escape and de-escape the elements, but there is a more sound solution to that.

First of all remind that you -always- want to set defaults for field values. Non-existing values cause trouble when the input is not as controlled as your initial test input. In Alfresco terms, a name or a creation date are always filled with a decent value, they will follow the Alfresco restrictions on allowed values. A title or description can have any value a geek can enter. Usually some point in time this can break your JSON and your Share dashlet (or any other reuse) will remain empty. A few months after development, no one knows why…

Imagine a  (read: one)  Alfresco Document as a result of whatever query (e.g. a Lucene query). In real life you can have a list as well, but for sake of simplicity, lets stick to the simple sample.

The  trick of this post is the  <#escape x as jsonUtils.encodeJSONString(x)>  … </#escape> part, this is where the encoding of the JSON string takes place. I started using this as a default syntax to prevent uncontrolled input to ruin my JSON…

"document" : [
<#if result?exists>
  "name" : "${result.properties.name}" ,
  "creator" : "${result.properties.creator}",
  "description" : <#escape x as jsonUtils.encodeJSONString(x)>  "${result.properties.description!""}"</#escape>,
  "title" : <#escape x as jsonUtils.encodeJSONString(x)> "${result.properties.title!""}" </#escape>

5 Responses to “JSON escaping in Freemarker”

  1. 1 Tony Cheung June 25, 2010 at 18:44

    That looks neat, but may I know where does jsonUtils coming from?

  2. 2 J.Jacobus Roos September 1, 2010 at 10:01

    Will such encoding enable me to insert binary data for a JPEG as well like xml CDATA ?

    or is that a bit to heavy for the jsonUtils.encodeJSONString method ?

    • 3 tpeelen December 3, 2010 at 22:50

      Sorry for being ‘a bit late’. [understatement]
      I think you usually will use json to supply all details to construct the links to the binary data, not the data itself…

  3. 4 brunocavalcante September 8, 2011 at 14:28

    awesome tip, thanks! 🙂

  1. 1 Review of ‘Alfresco 3 Cookbook’ by Snig Bhaumik « Open Source ECM/WCM Trackback on September 16, 2011 at 10:18
Comments are currently closed.