首页 > 解决方案 > 不是 Jenkins 和 Groovy 的那种 Map 异常

问题描述

我在 groovy 中有一个字符串,我想将其转换为地图。当我通过一个 groovy 脚本在本地计算机上运行代码进行测试时,我没有任何问题,并且返回了一个惰性映射。然后我可以将其转换为常规地图,然后生活继续。当我通过我的 Jenkins DSL 管道尝试相同的代码时,我遇到了异常

groovy.json.internal.Exceptions$JsonInternalException: Not that kind of map

这是有问题的代码块:

  import groovy.json.*

  String string1 = "{value1={blue green=true, red pink=true, gold silver=true}, value2={red gold=false}, value3={silver brown=false}}"

  def stringToMapConverter(String stringToBeConverted){
      formattedString = stringToBeConverted.replace("=", ":")
      def jsonSlurper = new JsonSlurper().setType(JsonParserType.LAX)
      def mapOfString = jsonSlurper.parseText(formattedString)
      return mapOfString
  }

  def returnedValue = stringToMapConverter(string1)

  println(returnedValue)

返回值:

[value2:[red gold:false], value1:[red pink:true, gold silver:true, blue green:true], value3:[silver brown:false]]

我知道 Jenkins 和 Groovy 在很多方面有所不同,但是从在线搜索中其他人建议我应该能够在我的 groovy 管道中使用 LAX JsonSlurper 库。我试图避免将我自己的字符串手动滚动到映射转换器,并且如果它在那里,我更愿意使用一个库。这里有什么不同会导致这种行为?

标签: jenkinsgroovyscripting

解决方案


尝试使用

import groovy.json.*

//@NonCPS
def parseJson(jsonString) {
    // Would like to use readJSON step, but it requires a context, even for parsing just text.
    def lazyMap = new JsonSlurper().setType(JsonParserType.LAX).parseText(jsonString.replace("=", ":").normalize())

    // JsonSlurper returns a non-serializable LazyMap, so copy it into a regular map before returning
    def m = [:]
    m.putAll(lazyMap)
    return m
}

String string1 = "{value1={blue green=true, red pink=true, gold silver=true}, value2={red gold=false}, value3={silver brown=false}}"
def returnedValue = parseJson(string1)
println(returnedValue)
println(JsonOutput.toJson(returnedValue))

您可以在normalize 此处找到有关信息。


推荐阅读