Search code examples
jenkinsgroovyjenkins-pluginsjenkins-groovy

how to access every key value in a json file and return them as a list in jenkins?


I have a list element that looks as follows:

[
    {
        "leaf101": {
            "node_id": "101",
            "node_name": "leaf101",
            "pod_id": "1"
        },
        "leaf102": {
            "node_id": "102",
            "node_name": "leaf102",
            "pod_id": "1"
        },
        "spine103": {
            "node_id": "103",
            "node_name": "spine103",
            "pod_id": "1"
        }
    }
]

I'm trying to give a list back to list them as variables in the Active choices parameter in Jenkins. My script looks as follows:

import groovy.json.JsonSlurper
def list = []

File textfile= new File("/var/lib/jenkins/test/vars/nodes.json")
JsonSlurper slurper = new JsonSlurper()
def parsedJson = slurper.parse(textfile)

parsedJson.each {
    list.add (it.node_name.toString())
}

return list;

Which returns nothing. If I type return parsedJson at the end I get the entire file content as one variable. How can I only return the key values like "leaf01,leaf02..."

Thanks in advance.


Solution

  • parsedJson.each {
        list.add (it.node_name.toString())
    }
    

    I think the problem with that is that it is the outer object which contains [leaf101:[node_id:101, node_name:leaf101, pod_id:1], leaf102:[node_id:102, node_name:leaf102, pod_id:1], spine103:[node_id:103, node_name:spine103, pod_id:1]], so it.node_name is not going to work. You will need to iterate a layer deeper into the model.

    For example, this will yield the result you expected:

        parsedJson.each { obj ->
            obj.each { k, v ->
                list.add v.node_name
            }
        }