Freemarker Container to JSON

Kind of a random post, but at work we’ve been trying to find a good way to dump a Freemarker object to JSON. I finally found a nice solution online, but it wasn’t even described as having the ability to do what it does, and now I can’t find the source of it. Hopefully this will help someone else out in the future, and if this code looks familiar, please let me know where it’s from so I can cite the source properly.

The following code will take a Freemarker sequence, hash, or collection (or a mixture of all three) and dump the contents to the page as JSON. It may work with other Freemarker data types as well, but I have not tested it. It’s currently a macro, but I think it would be fairly easy to convert it to a function as well.

<#macro objectToJsonMacro object> 
<@compress single_line=true> 
    <#if object?is_hash || object?is_hash_ex> 
        <#assign first="true"> 
        { 
        <#list object?keys as key> 
            <#if first="false">,</#if> 
            <#assign value><@objectToJsonMacro object=object<key> /></#assign> 
            "${key}" : ${value?trim} 
            <#assign first="false"> 
        </#list> 
        } 
    <#elseif object?is_enumerable> 
        <#assign first="true"> 
        [ 
        <#list object as item> 
            <#if first="false">,</#if> 
            <#assign value><@objectToJsonMacro object=item /></#assign> 
            ${value?trim} 
            <#assign first="false"> 
        </#list> 
        ] 
    <#else> 
        "${object?trim}" 
    </#if> 
</@compress> 
</#macro> 
This entry was posted in Web Development and tagged , , , . Bookmark the permalink.

2 Responses to Freemarker Container to JSON

  1. Kevin says:

    Is there any way to do the opposite – get JSON from your front-end JS into Freemarker?

    I know enough to be dangerous in FTL, and unfortunately, not enough to get past a current hurdle.

    • Eric Brandel says:

      Well, what ever is rendering the freemarker template on the server would be passing in the JSON. Freemarker itself cant accept a POST or PUT, so your server code would have to accept the data and then process it.

Leave a Reply

Your email address will not be published. Required fields are marked *


1 + nine =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>