Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 206
Katone Vi Avatar asked Mar 15 '19 00:03

Katone Vi


People also ask

What is import Groovy JSON JsonSlurper?

JsonSlurper is a class that parses JSON text or reader content into Groovy data. Structures such as maps, lists and primitive types like Integer, Double, Boolean and String. 2. JsonOutput. This method is responsible for serialising Groovy objects into JSON strings.

How do I call a Groovy script from Jenkins?

Usage. To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.

What is readYaml?

readYaml : Read yaml from files in the workspace or text. text : An Optional String containing YAML formatted datas. These are added to the resulting object after file and so will overwrite any value already present if not a new YAML document.


1 Answers

I finally find a BETTER solution!

readJSON() method from the Jenkins "Pipeline Utility Steps" plugin as shown here:

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.

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
    }
}
like image 53
Katone Vi Avatar answered Oct 19 '22 19:10

Katone Vi