handlebars.java icon indicating copy to clipboard operation
handlebars.java copied to clipboard

String as JSON context

Open Pfeil opened this issue 5 years ago • 1 comments

Hi, I have the situation that I have a String (from a http response body) containing JSON that shall be transformed using a template. The goal is JSON to JSON transformation (as described in the book "JSON for work"). I am doing it like this (prototypical):

// Optional<String> record_json = ... ;
Handlebars hb = new Handlebars();
String elastic_json = "";
try {
    Template template = hb.compile("mytemplate");
    elastic_json = template.apply(record_json.get());
} catch (Exception e) {
    LOG.debug("Could not build and apply template. {}", e);
    return RESULT.FAILED;
}

This is not yet perfect, as the quotation marks get removed on json values. I believe I can write a helper to fix this, but that is another topic I guess. In case this is possible with built in helpers, it would be nice to get a hint :)

The problem is that none of the variables get substituted. It should work though, as I prototyped with exact the same data and template using http://tryhandlebarsjs.com/ . I currently assume, that the string record_json is not handled as JSON data. In this case, how can I achive this? Or is the problem something else?

My template:

{
  "pid": "{{pid}}",
  {{#each entries}}
    "{{@key}}": [
      {{#each this}}
      {{{value}}}{{#unless @last}},{{/unless}}
      {{/each}}
    ]{{#unless @last}},{{/unless}}
  {{/each}}
}

Minimal example data:

{
    "pid": "tmp/test/-1190688899",
    "entries": {
        "21.T11148/397d831aa3a9d18eb52c": [
            {
                "key": "21.T11148/397d831aa3a9d18eb52c",
                "value": "2020-09-16T09:31:39.486+00:00"
            }
        ]
    }
}

Excerpt from the tryhandlebars.com result:

{
  "pid": "tmp/test/-1190688899",
    "21.T11148/397d831aa3a9d18eb52c": [
      2020-09-16T09:31:39.486+00:00
    ]
}

What I get from my code above:

{
    "pid": ,
}

Pfeil avatar Sep 17 '20 10:09 Pfeil

I got it working. I changes the code to something like this:

Template template = hb.compile("mytemplate");
JSONObject jsonData = new JSONObject(record_json.get());
Context c = Context
    .newBuilder(template)
    .combine(jsonData.toMap())
    .build();
elastic_json = template.apply(c);

Note that I used org.json:json to get the JSONObject type. Is this the way it is intended/recommended? If so, I think this issue can be closed.

Pfeil avatar Sep 17 '20 14:09 Pfeil