I have a controller in Play that passes a string in JSON format to a Scala view:
public Result reportsPieChart() {
String jsonString = "{cols: [{id: 'task', label: 'Task', type: 'string'}, {id: 'hours', label: 'Hours per Day', type: 'number'}],rows: [{c:[{v: 'Work'}, {v: 11}]}, {c:[{v: 'Eat'}, {v: 2}]}, {c:[{v: 'Commute'}, {v: 2}]}, {c:[{v: 'Watch TV'}, {v:2}]}, {c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}]}";
return ok(piechart.render(jsonString));
}
In the view, I am using this variable in the Javascript to display the Google Chart:
@(jsonString: String)
@main(null) {
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {
packages : [ 'corechart' ]
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonString = "@jsonString";
var newJSON = jsonString.replace(/'/g, "'");
console.log("newJSON: " + newJSON);
// Define the chart to be drawn.
var data = new google.visualization.DataTable(newJSON);
// Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
chart.draw(data, null);
}
</script>
<section id="displayResults" style="padding: 30px;">
<!-- Identify where the chart should be drawn. -->
<div id="myPieChart"/>
</section>
}
WHen passing the newJSON variable to the DataTable, it seems not to recognize it -- no errors, nothing to the console -- and does not display any charts.
The newJSON variable prints out to console in the correct format:
newJSON: {cols: [{id: 'task', label: 'Task', type: 'string'}, {id: 'hours', label: 'Hours per Day', type: 'number'}],rows: [{c:[{v: 'Work'}, {v: 11}]}, {c:[{v: 'Eat'}, {v: 2}]}, {c:[{v: 'Commute'}, {v: 2}]}, {c:[{v: 'Watch TV'}, {v:2}]}, {c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}]}
I am following the instructions from Google: https://developers.google.com/chart/interactive/docs/reference#datatable-class
In the example, I copied that JSON into my string.
Is there something I missing within Scala in a view to get this variable to work? According to Google, you can pass a literal string to the DataTable.
I appreciate the help!