jenkins-pipeline readJSON - how to read key elements as a list

Viewed 18358

I have trouble reading all keys "type-X.X" from JSON with readJSON

oldJson string:

{
"branch":{
    "type-0.2":{"version":"0.2","rc":"1","rel":"1","extras":"1"}}
    "type-0.3":{"version":"0.3","rc":"1","rel":"1","extras":"1"}}
}

I try to access it as in example https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

def branchList = new JsonSlurper().parseText(oldJson['branch'])
echo (branchList.keySet().toString())

but it fails:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (net.sf.json.JSONObject) values:

I would like to get a list ["type-0.2", "type-0.3"]

1 Answers

The JSON string you have provided is not valid. There is an extra } and a missing , after the first child element. It has to be:

{
"branch":{
    "type-0.2":{"version":"0.2","rc":"1","rel":"1","extras":"1"},
    "type-0.3":{"version":"0.3","rc":"1","rel":"1","extras":"1"}
    }
}

Now, you can parse this using the readJSON step in your pipeline to get a list of keys.

stage('Read-JSON') {
    steps {
        script {
            def oldJson = '''{
            "branch":{
                "type-0.2":{"version":"0.2","rc":"1","rel":"1","extras":"1"},
                "type-0.3":{"version":"0.3","rc":"1","rel":"1","extras":"1"}
                }
            }'''
            def props = readJSON text: oldJson
            def keyList = props['branch'].keySet()
            echo "${keyList}"
            // println(props['branch'].keySet())

        }
    }
}

Output:

[Pipeline] stage
[Pipeline] { (Read-JSON)
[Pipeline] script
[Pipeline] {
[Pipeline] readJSON
[Pipeline] echo
[type-0.2, type-0.3]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
Related