Search code examples
javascriptjsonfreemarker

Display JSON text in freemarker


JSON text:

[{"desc":null,"amount":250,"item":"527"},{"desc":"test","amount":3333.33,"item":"522"},{"desc":null,"amount":3333.33,"item":"522"},{"desc":null,"amount":1500,"item":"520"},{"desc":null,"amount":1560,"item":"519"}]

I tried the following Code but it is not working: <#assign customrecord = record.custpage_custrecord_itemlist?eval /> <#list customrecord as customrecord_line>

<#list customrecord as customrecord_line>

${customrecord_line.item}
${customrecord_line.desc}
${customrecord_line.amount}

</#list>

Note:(record.custpage_custrecord_itemlist is the variable that contains the json text) Please help

Thanks in advance!


Solution

  • Update: Since 2.3.31 there's ?eval_json for this. Not only it understands JSON null, but also it's safer, as it can't call the methods of the objects in the data-model (because it's not evaluated as FTL, just as JSON).

    There's no JSON parser built into the template language. ?eval parses FTL expressions, not JSON. The two happens to be similar, but not identical. Unlike in JSON, in FTL there's no null. So I guess the error you run into is that null is undefined. A possible workaround is that you do something like <#assign null=''> earlier, so when ?eval sees null, it replaces it with an empty string (which is not very good, but you see what the mechanism is; you could chose some other special value as well).

    But the only correct solution would be using a real JSON parser and put the result into the data-model (or to write a TemplateMethodModel that does calls a real JSON parser and returns the result).