28

How can I convert this String variable to a List ?

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

I tried with: as List and toList();

user2068981
  • 298
  • 1
  • 3
  • 6

4 Answers4

35
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,761
  • 1
  • 14
  • 17
30
def l = ids.split(',').collect{it as int}
animuson
  • 53,861
  • 28
  • 137
  • 147
Sergio Martinez
  • 925
  • 1
  • 7
  • 20
  • 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
30

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]
Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90
14

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
  • 645
  • 1
  • 6
  • 18
  • `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
  • 1
    The higher scoring answers didn't work for me. This one did. – Vladimir Oct 21 '19 at 13:44
  • Could you explain what exactly tokenize(',[]') doing here? – Raunak Kapoor Aug 25 '22 at 20:37
  • Without the brackets, you get [[a, b, c]] as a result. Not sure I understand how adding the brackets removes the additional outer list. – Nick Apr 11 '23 at 21:00