“Pretty” Formatting of GRAILS Controller rendered JSON

It's not uncommon when developing GRAILS applications that you want a controller to return a volume of data in the "JSON" format. The default controller code looks something like this..

def getData = {
    def rtn = [ ... some data .... ]
    render rtn as JSON
}

This code renders the data in a very compact format, which (if there is lots of it) makes reading by humans a little tricky.

If you want to be able to view the data yourself in order to understand it's contents better, you also have the option of outputting in a "pretty" format. This results in a larger volume of output, but includes spaces, tabs and new-lines to make the format more readable. In order to achieve this result, the controller code above can be modified as follows.

def getData = {
    def rtn = [ ... some data .... ]
    render new JSON(rtn).toString(true);
}
Scroll to Top