Convert String Variable to a List [Groovy]

How can I convert this String variable to a List ?

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

I tried with: as List and toList();

3

4 Answers

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.

7
def l = ids.split(',').collect{it as int}
5

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]
3

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]
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest