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>
}
</#if>
]
}

That looks neat, but may I know where does jsonUtils coming from?
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 ?
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…
awesome tip, thanks!