In a previous post, I wrote about using a Freemarker macro to dump a Freemarker container to JSON. That’s nice, but it limits you because macros dump the content directly to the page. It would be better to use a function. I tweaked the original macro to convert it into a function. The main thing to note was that instead of using assign, you need to use local. If you do not, the recursive function calls will step on each other’s variables.
The new objectToJsonFunction is as follows:
<#function objectToJsonFunction object>
<#local json = "">
<#if object?is_hash || object?is_hash_ex>
<#local first="true">
<#local json = json + '{'>
<#list object?keys as key>
<#if first="false"><#local json = json + ','></#if>
<#local value = objectToJsonFunction(object<key>) >
<#local json = json + '"${key}": ${value?trim}'>
<#local first="false">
</#list>
<#local json = json + '}'>
<#elseif object?is_enumerable>
<#local first="true">
<#local json = json + '['>
<#list object as item>
<#if first="false">
<#local json = json + ','>
</#if>
<#local value = objectToJsonFunction(item) >
<#local json = json + '${value?trim}'>
<#local first="false">
</#list>
<#local json = json + ']'>
<#else>
<#local json = json + '"${object?trim}"'>
</#if>
<#return json>
</#function>