Reputation: 59
I have a list of lists passed in from view like this:
[lists:[["e","q"],["t","w"]], action:save, controller:newReport]
in my controller
def lists = params.lists;
the lists will be a string which has value of "[["e","q"],["t","w"]]"
how should I iterate through the list to get each sublist?
Upvotes: 1
Views: 4278
Reputation: 5770
Use JSON.parse:
groovy:000> lists = JSON.parse("[['e', 'q'], ['w', 'q']]")
===> [["e","q"],["w","q"]]
groovy:000> lists.each { list -> println list }
[e, q]
[w, q]
===> [["e","q"],["w","q"]]
groovy:000> lists[0].each { entry -> println entry }
e
q
===> ["e","q"]
This is much more secure than a GroovyShell. That way you don't have to think about how to secure it or how to use a regex to parse the string.
Upvotes: 3
Reputation:
Grails have a good type conversion that you can use in params
.
Have you tried params.list('lists')
?
EDIT:
Tried now here, in your case you can evaluate the expression to transform in a list:
params.lists = '[["e","q"],["t","w"]]'
def listValues = new GroovyShell().evaluate(params.lists)
listValues.each { list ->
println list
println list.class.canonicalName
}
EDIT2: This may be dangerous if the user send another content that's not expected. You can secure your GroovyShell as explained in this post.
Upvotes: 0