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
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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