[Play-Java 2.6] Json data and template

I’ve to plot a chart passing Json data to the template.
The data has to be in the following form:
data: [
{ y: ‘Turno A’, a: 100 },
{ y: ‘Turno B’, a: 75 },
{ y: ‘Turno C’, a: 50 },
{ y: ‘Turno D’, a: 75 }

In my Play controller I use the following method to create the Json object:

public Result statistics() {
        ArrayList<Map<Object, Serializable>> all = new ArrayList<Map<Object, Serializable>>();
        List<Tourn> t = tourn.findAll();
        for(Tourn tr: t) {
            Map<Object, Serializable> details = new HashMap<Object, Serializable>();
            details.put("y", tr.getName());
            details.put("a", student.countAllByTourn(tr.getName()));


        return ok(statistics.render(play.libs.Json.toJson(all)));


It’s print:
[{a=2, y=Turno A}, {a=1, y=Turno B}]

In the template I have:

@import com.fasterxml.jackson.databind.JsonNode
@(all: JsonNode)

<script type="text/javascript">
        $(function() {
                element: 'flot-bar-chart',
                data: @all,
                xkey: 'y',
                ykeys: ['a'],
                labels: ['Turni',]



But checking the source page the all variable was converted in:
data: [{&quot;a&quot;:2,&quot;y&quot;:&quot;Turno A&quot;},{&quot;a&quot;:1,&quot;y&quot;:&quot;Turno B&quot;}],

so the chart isn’t displayed.

Is there a solution for that?

Try using data: decodeURI(@all) to un-escape the escape characters. Not sure if that will work syntactically, but the idea to un-escape those characters.


Doesn’t work.
Now in the source, I’ve:

data: decodeURI([{&quot;a&quot;:3,&quot;y&quot;:&quot;Turno A&quot;},{&quot;a&quot;:1,&quot;y&quot;:&quot;Turno B&quot;}]),

Try @Html(all)

1 Like

Also, be aware of cross-site scripting when using @Html(all). If your json contains </script><script> .. </script><script>, it’s gonna cause an issue.

I suggest encoding the data in Base64 and decode it in Javascript. An example is here: https://github.com/GIVESocialMovement/sbt-vuefy/blob/master/test-play-project/app/views/index.scala.html#L19

This doesnt’ work:

type mismatch;
found : com.fasterxml.jackson.databind.JsonNode
required: String

Try @Html(all.toString)

1 Like

Thanks!!! It’s working