Tuesday, February 26, 2013

Generic printing of properties in complex javascript object

I needed to make a generic solution for printing ScriptNode and the like object to JSON using FreeMarker, without knowing which keys to include before the script runs ... So I wanted just to print all property like key and value pair (String/String).

Turns out this is a little cumbersome, so here is my 5 cents:

<#assign keys=item?keys>
<#assign values=item?values>
<#assign max=keys?size>
<#assign jsonIndex=0>
{

 <#list 0..max as index>
  <#if keys[index]?exists>
   <#if keys[index]?is_string>
    <#if values[index]?exists>
     <#if values[index]?is_string>
      <#if jsonIndex!=0>,

      <#else>
       <#assign jsonIndex=jsonIndex+1>
      </#if>
"${keys[index]}" : "${values[index]}"
     </#if>
    </#if>
   </#if>
  </#if>
 </#list>

}

Well, what does it do ... it keeps two different indexes, one for the key/value pair being processed and one for number of json lines added for adding commas. It seems FreeMarker cannot handle Hashes with non-strings, so to bypass this restriction you must index your way through and test for existens and for type being String. This is done over the keys and values sequences, which are read from item (Javascript object, which become a FreeMarker SimpleHash).