25

How can I convert this String variable to a List ?

def ids = "[10, 1, 9]"

I tried with: as List and toList();

user2068981
  • 268
  • 1
  • 3
  • 6

4 Answers4

34
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.

Rick Mangi
  • 3,721
  • 1
  • 12
  • 16
27
def l = ids.split(',').collect{it as int}
animuson
  • 52,378
  • 28
  • 138
  • 145
Sergio Martinez
  • 866
  • 1
  • 7
  • 19
  • I think you want to make a string "10,1,9" into a list [10,1,9] – Sergio Martinez Feb 28 '13 at 00:17
  • def id = ids.substring(1,ids.length()-1) def l= id.split(',').collect{it as int} – user2068981 Feb 28 '13 at 00:44
  • 1
    I find this solution but I don't think is the best : def id = ids.substring(1,ids.length()-1) def l= id.split(',').collect{it as int} – user2068981 Feb 28 '13 at 00:48
  • this works great for me, specifically in Jenkins, and using String instead of Int: `files = "'f1','f2'" list = files.split(',').collect{it as String} > list==['f1', 'f2'] > list[1]=='f2' ` – Max Cascone Nov 10 '20 at 20:28
  • updating mine after the edit window closed: `list = versionFile.split(',').collect()` works fine for strings. – Max Cascone Nov 10 '20 at 20:38
25

Use the built-in JsonSlurper!

Using Eval is dangerous 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]
Alexander Suraphel
  • 9,083
  • 9
  • 48
  • 86
11

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]
TangHongWan
  • 555
  • 1
  • 4
  • 13
  • `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]'" – CIsForCookies Sep 19 '19 at 12:12
  • The higher scoring answers didn't work for me. This one did. – Vladimir Oct 21 '19 at 13:44