How can I convert this String
variable to a List
?
def ids = "[10, 1, 9]"
I tried with: as List
and toList();
How can I convert this String
variable to a List
?
def ids = "[10, 1, 9]"
I tried with: as List
and toList();
def l = Eval.me(ids)
Takes the string of groovy code (in this case "[10,1,9]") and evaluates it as groovy. This will give you a list of 3 ints.
def l = ids.split(',').collect{it as int}
Use the built-in JsonSlurper!
Using Eval
could be risky as it executes any code and the string manipulation solution will fail once the data type is changed so it is not adaptable. So it's best to use JsonSlurper.
import groovy.json.JsonSlurper
//List of ints
def ids = "[10, 1, 9]"
def idList = new JsonSlurper().parseText(ids)
assert 10 == idList[0]
//List of strings
def ids = '["10", "1", "9"]'
idList = new JsonSlurper().parseText(ids)
assert '10' == idList[0]
This does work for me. And Eval.me
will not work in Jenkins groovy script. I have tried.
assert "[a,b,c]".tokenize(',[]') == [a,b,c]