ThanosFisherman
ThanosFisherman

Reputation: 5859

Add double quotes to list of strings

I've got a list in groovy lets say:

[one, two, three]

Now I want to add double quotes to the strings of this array so that the final result would be:

["one", "two", "three"]

Note that I do want the square brackets to be included as well. How can I do that in Groovy in the most comprehensive way?

EDIT: I'm using groovy templating inside html code and I just want a string in the exact format I described above

Upvotes: 10

Views: 21925

Answers (3)

ThanosFisherman
ThanosFisherman

Reputation: 5859

Since inspect() method adds single quotes instead of doubles in groovy templating for some reason, best solution I came up with is this

${myList.inspect().replaceAll("\'", "\"")}

output: ["one", "two", "three"]

My solution along with Prakash solution are the only ones that worked for me.

Upvotes: -1

Prakash Thete
Prakash Thete

Reputation: 3892

so if you have:

def list = ['one', 'two', 'three']

Then you can do:

List modifiedList = list.collect{ '"' + it + '"'}

output : ["one", "two", "three"]

Upvotes: 22

tim_yates
tim_yates

Reputation: 171054

so if you have:

def list = ['one', 'two', 'three']

Then you can do:

String strList = list.inspect()

To get the list quoted and with square brackets

An alternative would also be to do:

String strList = new groovy.json.JsonBuilder(list).toString()

Which will give you the same, but in json format (with double quotes)

Upvotes: 7

Related Questions