nirvair
nirvair

Reputation: 4180

groovy: convert string (which is a list) to a Groovy List

import groovy.json.JsonSlurper

def ver = "['a', 'b', 'c']"
def jsonSlurper = new JsonSlurper()
def ver_list = jsonSlurper.parseText(ver)
println ver_list

This is what I'm doing. I want to iterate over ver_list. And it seems difficult to find a solution for it.

This is the error when I print ver_list:

Caught: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']
.^
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']

Upvotes: 1

Views: 649

Answers (1)

daggett
daggett

Reputation: 28634

the valid json strings must be double-quoted.

so change in your code this line and it should work:

def ver = '["a", "b", "c"]'

however if you need to parse not a valid json you could try LAX parser.

then even the following string could be parsed

import groovy.json.JsonSlurper
import groovy.json.JsonParserType

def ver = "[a, 'b', 001]"
def jsonSlurper = new JsonSlurper().setType( JsonParserType.LAX )
def ver_list = jsonSlurper.parseText(ver)
println ver_list

Upvotes: 2

Related Questions