Search code examples
grailsgsp

How do I pass a JSON array to a JavaScript variable on my GSP page?


I have the following Controller Action:

def doSomething() {
  [data: data as JSON]
}

On my GSP I can output the data params with:

${data}

Since data represents valid JSON I want to use it inside a JavaScript block on my GSP.

<script type="text/javascript">
var data = [
            { Date: "2015-09-14", DayOfMonth: 14, Type: "Views", Amount: 0, y1: 10, }
           ];
</script>

To replace a hard coded JSON variable. I know I can do the replacement with Strings like this:

<script type="text/javascript">
var data = "${data}";
</script>

or

<script type="text/javascript">
var data = "${raw(data)}";
</script>

The former works fine work primitive types like Strings but if I pass the JSON Array to the JavaScript variable it fails. When I print the content of the JavaScript data variable in the console I get:

[{&quot;Date&quot;:&quot;2015-09-13T22:00:00Z&quot;,&quot;DayOfMonth&quot;:14,&quot;Type&quot;:&quot;Views&quot;,&quot;Amount&quot;:1}]

How do I pass a JSON array to a JavaScript variable on my GSP page?


Solution

  • It appears to be an encoding problem that has yet to be resolved.

    Solution 1 - disable encoder locally

    <g:applyCodec encodeAs="none">
        var data = ${data};
    </g:applyCodec>
    

    Solution 2 - Affects the whole page

    <%@page defaultCodec="none" %>
    

    Solution 3 - Use a custom tag

    class MyTagLib {
        static defaultEncodeAs = [taglib:'none']
    
        def writeWithoutEncoding = {attrs ->
            out << attrs.input
        }
    }
    

    and in the GSP page:

    var data = <g:writeWithoutEncoding input="${data}"/>;
    

    References: https://jira.grails.org/browse/GRAILS-11829 and http://aruizca.com/how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag/