Search code examples
groovyjenkins-groovyjenkins-scriptler

Transpose list in groovy


I want to transpose this list in a groovy script. There are two lists

result_name = ["API (example)","Management Portal (example)","Component1","Component2",]

result_ids = ["3wrhs4vp3sp5","g2828br1gzw9","68pnwhltxcq0","fy8g2nvvdg15",]

I am expecting an output like list[0][0], list[1][1].... example:

API (example) 3wrhs4vp3sp5
Management Portal g2828br1gzw9
Component1 68pnwhltxcq0
Component2 fy8g2nvvdg15

I am trying this using

def result = [[result_name], [result_ids]].transpose()

but the result is:

Result: [[["API (example)","Management Portal (example)","Component1","Component2",], ["3wrhs4vp3sp5","g2828br1gzw9","68pnwhltxcq0","fy8g2nvvdg15",]]]

EDIT: Updated sample code in the question:

proc1 = ['/bin/bash', '-c', "curl https://api.statuspage.io/v1/pages/lbh0g6b5mwnf/components?api_key=<key>"].execute()
proc2 = ['/bin/bash', '-c', "grep -Po '\"name\": *\\K\"[^\"]*\"'| tr '\n' ', '"].execute()
proc3 = ['/bin/bash', '-c', "curl https://api.statuspage.io/v1/pages/lbh0g6b5mwnf/components?api_key=<key>"].execute()
proc4 = ['/bin/bash', '-c', "grep -Po '\"id\": *\\K\"[^\"]*\"'| tr '\n' ', '"].execute()

all_name = proc1 | proc2
all_ids = proc3 | proc4
def result_name = [all_name.text]
def result_ids = [all_ids.text]

println result_name
println result_ids

def result = [result_name, result_ids].transpose()

Result

["API (example)","Management Portal (example)","Component1","Component2",]
["3wrhs4vp3sp5","g2828br1gzw9","68pnwhltxcq0","fy8g2nvvdg15",]
Result: [["API (example)","Management Portal (example)","Component1","Component2",, "3wrhs4vp3sp5","g2828br1gzw9","68pnwhltxcq0","fy8g2nvvdg15",]]
 

Solution

  • Answering my own question.

    After a few debugging, I realized that my list is having a single string and because of that split() was not expecting that weird input. I was able to print the first String by putting in newstr and then split(',') code below:

    all_name = proc1 | proc2
    all_ids = proc3 | proc4
        
    result_name = [all_name.text]
    result_ids = [all_ids.text]
    
    newstr = result_name[0]
    result_newstr = newstr.split(',')
    
    newids = result_ids[0]
    result_newids = newids.split(',')
    
    def aa = []
    for(int i = 0;i< result_newstr.size(); i++) {
        a = result_newstr[i].concat(" ").concat(result_newids[i])
      aa.add(a)
    }
    return aa
    

    This results:

    "API (example)" "3wrhs4vp3sp5"
    "Management Portal (example)" "g2828br1gzw9"
    "Component1" "68pnwhltxcq0"
    "Component2" "fy8g2nvvdg15"