jenkins-pipeline readJSON - 如何以列表形式读取关键元素

Woj*_*Zet 3 groovy jenkins jenkins-plugins jenkins-groovy jenkins-pipeline

我无法使用 readJSON 从 JSON 读取所有键“type-XX”

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"}}
}
Run Code Online (Sandbox Code Playgroud)

我尝试访问它,例如 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())
Run Code Online (Sandbox Code Playgroud)

但它失败了:

hudson.remoting.ProxyException:groovy.lang.MissingMethodException:没有方法签名:groovy.json.JsonSlurper.parseText()适用于参数类型:(net.sf.json.JSONObject)值:

我想要一个列表 ["type-0.2", "type-0.3"]

Dib*_*tya 6

您提供的 JSON 字符串无效。第一个子元素之后有一个额外的}和一个缺失。,它一定要是:

{
"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"}
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用管道中的步骤解析它readJSON以获取键列表。

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())

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

[Pipeline] stage
[Pipeline] { (Read-JSON)
[Pipeline] script
[Pipeline] {
[Pipeline] readJSON
[Pipeline] echo
[type-0.2, type-0.3]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
Run Code Online (Sandbox Code Playgroud)