How to render JSON properly (without escaping quotes) inside a GSP script tag

Angel Ruiz grails, how-to, javascript, json

Grails logo

This issue was encountered while using Grails version 2.3.11

In theory it should be as simple as:

  1. Return JSON in your model from your controller
def index() = {
	[data: data as JSON]
  1. Render the model attribute without encoding using the raw() method
	var data = ${raw(data)};

Unfortunately this does not work, at least when you are using the resources plugin.

You know it does not work because all the quotes have been escaped and they should have not:

	var data = {&quot;whatever&quot;:&quot;whatever&quot;};

It took me a while to find a way of doing it using the applyCodec taglib. Just replace the previous second step with this:

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

as a result you will see that is has been rendered properly:

	var data = {"whatever":"whatever"};

Link to related issues:


You can also use gsp page directives like these ones to set the encoding mechanism on a single page basis:
- Remove enconding from EL expressions:

<%@ expressionCodec="none" %>
  • Remove encoding from scriplets:
<%@ scriptletCodec="none" %>
  • Remove encoding everywhere in the page:
<%@ defaultCodec="none" %>
Share this post: