How to escape json strings in freemarker
Use a FreeMarker macro to combine all of the answers above, while making the template more readable and maintainable:
<#macro json_string string>${string?js_string?replace("\\'", "\'")?replace("\\>", ">")}</#macro>
{
"field1" : "<@json_string "${response.value1}"/>",
"field2" : "<@json_string "${response.value2}"/>"
}
If you want to reuse the macro in multiple templates, put it in its own file and include the file instead of duplicating the macro:
<#include "/path/to/macro.ftl">
You're looking for the ?js_string
operator.
{
"field1" : "${response.value1?js_string}",
"field2" : "${response.value2?js_string}"
}
That will take care of escaping quotes, backslashes, et. al in order to make your JS happy.
Edit: I just saw that they introduced a ?json_string
operator in Freemarker 2.3.19. See here for exactly how it works. And there was much rejoicing...