shanwar shanwar - 2 months ago 25
Groovy Question

Parse a JSON Array in gsp

I have this JSON array eg:

filesList
which I receive from my groovy controller:

[{"filenameAndPath":"a","description":"bb"}, {"filenameAndPath":"c","description":"d"},{"filenameAndPath":"e","description":"f"}]


In my gsp I want to render this into a format as such:

Filename and Path
a
Description
bb
Filename and Path
c
Description
d
Filename and Path
e
Description
f


How would I parse the JSON into such labels and fields in a gsp page?

Answer

Parse the JSON string in the controller first using the grails.converters.JSON.parse(jsonString) method, then pass the resulting object into your view and iterate over the arrays and objects using the g:each tag.

When iterating over objects/map entries (like in your {"filenameAndPath":"a","description":"bb"} example), you can use the nice shorthand syntax: <g:each in="${map}" var="key, value">..</g:each>

For the rest ordinary HTML should be enough.

Comments