Search code examples
jsontemplatesyamlfreemarkersnakeyaml

Freemarker template parser or snakeyaml does not print json strings as expected


We are trying to print out a json formatted string as a value for in yaml file without quotes. We are using Freemarker template engine version 2.3.26 and dumping the output in yaml files using org.yaml.snakeyaml library.

We either see json converted to yaml or json surrounded with single quotes; even though https://try.freemarker.apache.org/ seems to show it is possible.

Following are few examples with code snippet and corresponding output:

<#assign a = '{"key": "val"}'>
setting_a: ${a?string}

prints (without quotes)

string_a:
  key: val


<#assign a = '{"key": "val"}'>
setting_a: ${a?js_string}

prints (with quotes and escaping)

setting_a:
  \"key\": \"val\"


<#assign a = "{"key": "val"}">
setting_a: ${a?json_string}

prints (with quotes and escaping)

setting_a:
  \"key\": \"val\"


<#assign a = "{\"key\": \"val\"}">
setting_a: ${a?string}

prints (without quotes)

setting_a:
    key: val


<#assign a = "{"key": "val"}">
setting_a: ${a?js_string}

prints (with quotes and escaping)

setting_a:
  \"key\": \"val\"


<#assign a = "{"key": "val"}">
setting_a: ${a?json_string}

prints (with quotes and escaping

setting_a:
  \"key\": \"val\"

What we are expecting is output yaml file is

setting_a: {"key": "val"}.

  • Is this possible?
  • If so, do we need to select specific org.yaml.snakeyaml.DumperOptions for this?
  • If this is not possible, I am wondering if I am choosing incorrect options on https://try.freemarker.apache.org/

Solution

  • The first example prints {"key": "val"} in any version of FreeMarker. So I guess you are showing the result of parsing the output of the template as YAML. (While https://try.freemarker.apache.org shows the template output as is.) In that case, I think it should be: setting_a: "${a?js_string}".

    Also, <#assign a = "{"key": "val"}"> is syntax error in FreeMarker, and so you shouldn't get any output.