user1666450
user1666450

Reputation: 59

How to extract a list from params in controller

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

Answers (2)

Nicholas
Nicholas

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

user800014
user800014

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

Related Questions