1

I need to iterate this Map with all predecessor keys in groovy which I need to run through Jenkins.

a={b={c=1,d=2,e=3},r={p=4},q=5}

I want output like below and input is dynamic and format may vary. Please help since 1 week I am trying.

a:b:c=1

a:b:d=2

a:b:e=3

a:r:p=4

a:q=5
injecteer
  • 20,038
  • 4
  • 45
  • 89
Amit
  • 15
  • 3

1 Answers1

1

You can use a recursive function to achieve this result, here is an example:

def iterateMap(Map map, String prefix = "") {
    map.each { key, value ->
        if (value instanceof Map) {
            iterateMap(value, "$prefix$key:")
        } else {
            println "a:$prefix$key=$value"
        }
    }
}

def a = [
    b: [
        c: 1,
        d: 2,
        e: 3
    ],
    r: [
        p: 4
    ],
    q: 5
]

iterateMap(a)

In this code, the iterateMap function takes a map as input and an optional prefix string (initialized as an empty string). It iterates over each key-value pair in the map. If the value is itself a map, the function recursively calls itself with the nested map and the updated prefix ("$prefix$key:"). If the value is not a map, it prints the key-value pair in the desired format ("$prefix$key=$value").

Paulo Victor
  • 196
  • 1
  • 4
  • Thanks a lot!! I am new in groovy as well as Jenkins, can you please suggest how can I call from Jenkins inside script. Tried to call directly while reading yaml and same map object passing into that method seems i am getting error. – Amit May 15 '23 at 22:38
  • You need to use Pipelines. https://www.jenkins.io/doc/book/pipeline/ Related question: https://stackoverflow.com/questions/47628248/how-to-create-methods-in-jenkins-declarative-pipeline – Paulo Victor May 15 '23 at 23:32