简体   繁体   English

groovy:将字符串(列表)转换为 Groovy 列表

[英]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 .我想遍历ver_list And it seems difficult to find a solution for it.而且似乎很难找到解决方案。

This is the error when I print ver_list:这是我打印 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']

the valid json strings must be double-quoted.有效的 json 字符串必须用双引号引起来。

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.但是,如果您需要解析无效的 json,您可以尝试 LAX 解析器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM