1

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?

4
  • Why not do the work in the controller, rather than entrenching this sort of thing in the view? Commented Sep 15, 2016 at 19:00
  • Also, do you mean you send that to the GSP as a String of JSON text? Or are you sending a list of maps? Commented Sep 15, 2016 at 19:04
  • I would need the parameters from these <g:fields> in another controller. Is there a better way to design this ? Commented Sep 15, 2016 at 19:04
  • Actually this is a String of JSON text Commented Sep 15, 2016 at 19:24

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

To Parse a json string it is as defined by Gregor above. The only thing to watch out for is json null in string which needs to be converted into a real null.

Here is a function to convert a json string to a map

Map parseJSONSelection(String jsonString) {
       def u=[]
       def m=[:]
       if (userSelection) {
           def item=JSON.parse(userSelection)
           item?.each {JSONObject  i->
               // when an element could be null set it to real null
               if (JSONObject.NULL.equals(i.field)) {
                   i.field=null
               }
               u << i
           }
           m.allfilesAndPaths=item?.collect{it.filenameAndPath}
           m.results=u
       }
       return m
   }

now in the map returned it will contain map.results which will be the iteration of the json string that you pass to your gsp.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.