jenkins-pipeline readJSON - how to read key elements as a list
15,248
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 videos on Youtube
Author by
Wojtas.Zet
Updated on June 04, 2022Comments
-
Wojtas.Zet almost 2 years
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"]
-
Wojtas.Zet over 4 years
println(props['branch'].keySet())
works fine, but for some reason I cannot print it withecho
It works withprintln
... -
Dibakar Aditya over 4 yearsContrary to Groovy
println
,echo
does not evaluate the expression within it. To echo the list you need to first store it in a variabledef keyList = props['branch'].keySet()
and then call echo on it as a GString for interpolationecho "${keyList}"
.