I'm using Grails 2.3.7 and I have a controller action as follows:
def testData(){
def result = [:]
result['name'] = "Sales"
result['type'] = "bar"
result['data'] = [5, 20, 45, 10, 10, 20]
[data: result as JSON]
}
In the testData.gsp I'd like to get the JSON object in javascript:
<script>
$(document).ready(function(){
var data = JSON.parse(${data});
})
</script>
Then I got an exception:
Uncaught SyntaxError: Unexpected token {
on the line:
var data = JSON.parse({"name":"Sales","type":"bar","data":[5,20,45,10,10,20]});
It looks like JSON is messed up. I think it used to work this way. Maybe it's new Grails? How can I fix this? Thanks.
Update: Problem solved. See the comments in the accepted answer.
Update2: When I check the app today, it failed again. I did what the docs required with the "raw" method but no luck. A workaround is to use the "Per Page Encoding". This one I tested thoroughly. It does work.
g:set
and ${data} would give you the JSON String. Any reason you want it in script block.