在 Jenkins Pipeline 上解析 JSON (groovy)

Kat*_* Vi 15 groovy json jenkins jsonparser

我创建了一个方法,如在线所示:

@NonCPS
def parseJsonString(String jsonString) {
    def lazyMap = new JsonSlurper().parseText(jsonString)

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

但我收到以下错误:

错误:java.io.NotSerializableException:groovy.json.internal.LazyMap

为了解决这个问题,我必须创建一个完整的方法来执行整个步骤。例如,在一个方法中,我会做与上面相同的操作,解析我想要的信息,最后将其作为字符串返回。

然而,这带来了另一个问题,尤其是如果您将此方法包装在 a 中withCredentials,则需要另一个withCredentials.

Kat*_* Vi 38

我终于找到了更好的解决方案!

Jenkins“Pipeline Utility Steps”插件中的 readJSON() 方法,如下所示:

https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

这是一个示例,我们最终可以在其中抛弃丑陋的 GROOVY JSONPARSE 废话。

node() {
    stage("checkout") {
        def jsonString = '{"name":"katone","age":5}'
        def jsonObj = readJSON text: jsonString

        assert jsonObj['name'] == 'katone'  // this is a comparison.  It returns true
        sh "echo ${jsonObj.name}"  // prints out katone
        sh "echo ${jsonObj.age}"   // prints out 5
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 尝试“readJSON”而不是“readJson”。确保安装了“Pipeline Utility Steps”插件。 (2认同)