Parse model to json on gsp in grails

Posted By : Akash Sharma | 16-Feb-2014

Sometimes we have a requirement to pass data as model from controller action but we need it as a json object on gsp.

Below is the code snippet that works the same.

Let say I have a Person domain.I am passing it as a model but need it as JSON on gsp.

I am printing the converted JSON object in browser console.

 

Controller code

def index(){
 ArrayList listOfPerson=Person.list()
 [listOfPerson:listOfPerson]
}

 

GSP code

<%! import grails.converters.JSON %>
<html>
<head>
<meta name="layout" content="main">
<g:javascript library="jquery"></g:javascript>
</head>
<body>


<script>
function parseModelToJS(jsonString)
{
 jsonString=jsonString.replace(/\"/g,'"');
 var jsonObject=$.parseJSON(jsonString);
 return jsonObject
}

$(document).ready(function(){
 var listOfPerson=parseModelToJS('${listOfPerson as JSON}');
 console.log(listOfPerson);
});

</script>
</body>
</html>

 

Thanks

 

About Author

Author Image
Akash Sharma

Akash is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Akash loves playing Cricket and Tennis

Request for Proposal

Name is required

Comment is required

Sending message..