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}
files = "'f1','f2'" list = files.split(',').collect{it as String} > list==['f1', 'f2'] > list[1]=='f2' list = versionFile.split(',').collect() works fine for strings.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]
Eval.me didn't work for me as well (Jenkins groovy script). However, your solution gave a wrong result. My str is "['/a/b/c/d@2/e/f/g/h/i/j/k/l.py::m[n-10-3-9-0/8-17-12]',]" (actually I have more entries in the string, but this is the general idea). The tokenize returns only the inner list, i.e. "[n-10-3-9-0/8-17-12]'"
Listdo you want to convert it to aString?