简体   繁体   English

在 Jenkins Pipeline 上解析 JSON (groovy)

[英]Parsing JSON on Jenkins Pipeline (groovy)

I created a method as shown online:我创建了一个方法,如在线所示:

@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
}

But I get the following error:但我收到以下错误:

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

To work around this, I have to create an entire method to perform an entire step.为了解决这个问题,我必须创建一个完整的方法来执行整个步骤。 For instance, in a method, I would do the same as above, parse the information I want, and finally return it as a string.例如,在一个方法中,我会做与上面相同的操作,解析我想要的信息,最后将其作为字符串返回。

This, however, presents another issue, especially if you wrap this method inside a withCredentials , which would then require another withCredentials .然而,这带来了另一个问题,特别是如果您将此方法包装在withCredentials ,这将需要另一个withCredentials

I finally find a BETTER solution!我终于找到了更好的解决方案!

readJSON() method from the Jenkins "Pipeline Utility Steps" plugin as shown here: Jenkins“Pipeline Utility Steps”插件中的 readJSON() 方法,如下所示:

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

Here is a sample where we can finally ditch that ugly GROOVY JSONPARSE crap.这是一个示例,我们最终可以在其中抛弃丑陋的 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
    }
}

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

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