Jenkinsfile - JsonSlurper 返回字符串而不是地图

DVG*_*DVG 3 groovy jenkins jenkins-pipeline

所以我正在尝试一个嵌入了 config.json 文件的 CI 构建。

config.json
{
  "some_collection": [
    { "foo": "bar" }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我的詹金斯文件:

import groovy.json.JsonSlurper

node {
  bootstrap()
  test()
}
def bootstrap() {
  stage('bootstrap') {
    git([url: "git@github.com:my-user/my-jenkinsfile-repo.git"])
  }
}

def test() {
  def config = getConfig()
  echo "${config}"
  echo "${config.class}"
}

@NonCPS
def getConfig() {
  new JsonSlurper().parseText(readFile("./config.json")))
}
Run Code Online (Sandbox Code Playgroud)

配置对象的回显显示了文件中的 json,并且 config.class 表示是一个普通的旧字符串。我期待代码返回一个地图。

我尝试过 JsonSlurper 和 JsonSluperClassic,我也尝试过我能想到的所有方法来重组代码以使其更加明确,但我已经没有想法了。

编辑:我尝试添加一些强类型:

def getConfig() {
  JsonSlurper parser = new groovy.json.JsonSlurper()
  def json = readFile("./config.json")
  Map parsedJson = parser.parseText(json)
  return parsedJson
}
Run Code Online (Sandbox Code Playgroud)

这仍然会导致 config.class 作为字符串返回

小智 6

使用默认库在 Jenkins 中处理 JSON 是一团糟。只需使用readJSONPipeline Utility Steps 插件中的步骤即可。 https://github.com/jenkinsci/pipeline-utility-steps-plugin/blob/master/docs/STEPS.md