SteelwingsJZ SteelwingsJZ - 3 months ago 22
JSON Question

Sending JSON to javascript on GSP

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({&quot;name&quot;:&quot;Sales&quot;,&quot;type&quot;:&quot;bar&quot;,&quot;data&quot;:[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.

Answer

The problem is that the JSON is being encoded as HTML. Try the following instead:

Controller

def testData() {
    def result = [:]
    result['name'] = "Sales"
    result['type'] = "bar"
    result['data'] = [5, 20, 45, 10, 10, 20]
    [data: result as JSON]
}

GSP

<script>
    var data = ${raw(data)};
</script>

You don't need $(document).ready because the JS code

var data = ${raw(data)};

is generated on the server-side

Comments