Freemarker parse a String as Json

user1125394 picture user1125394 · Oct 26, 2012 · Viewed 29k times · Source

Probably it's not possible,
but I would like to transform a json string in a map with freemarker

ex:

<#assign test = "{\"foo\":\"bar\", \"f\":4, \"text\":\"bla bla\"}">

and be able to get the text key from this string

Answer

ddekany picture ddekany · Oct 26, 2012

Use ?eval. It works because JSON maps happen to be valid FreeMarker expressions (update: except that null is not recognized in FreeMarker 2.3.x).

<#assign test = "{\"foo\":\"bar\", \"f\":4, \"text\":\"bla bla\"}">
<#assign m = test?eval>

${m.foo}  <#-- prints: bar -->

<#-- Dump the whole map: -->
<#list m?keys as k>
  ${k} => ${m[k]}
</#list>

(BTW, you don't have to use \" if you quote the string with ' instead of ".)