Mick Feller
Mick Feller

Reputation: 892

Convert groovy string to map in jenkins pipeline

I'm fairly new to Groovy and Jenkins pipelines and i need a string converted to a map to get some workable data i haven't been able to find a solution so far.

[fileListJs:file1.js,file2.js,file3.js, fileListHtml:file4.html,file5.html,file6.html, fileListCss:file6.css,file7.css,file8.html]

The string above is what a certain jenkins choice parameter is returning me in a groovy variable. Now i need this to be a proper map to be able to parse the data in there.

So i tries this approach: Groovy String To map

Which does the following code:

def fileMap =
    // Take the String value between
    // the [ and ] brackets.
    fileList[1..-2]
        // Split on , to get a List.
        .split(', ')
        // Each list item is transformed
        // to a Map entry with key/value.
        .collectEntries { entry ->
            def pair = entry.split(':')
            [(pair.first()): pair.last()]
        }

Where fileList is the variable that has returned the previous given string.

But this is not working.

Any help is greatly appreciated.

Thanks

Upvotes: 0

Views: 5076

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

I believe this is what you are looking for.

String fileList = "[fileListJs:file1.js,file2.js,file3.js, fileListHtml:file4.html,file5.html,file6.html, fileListCss:file6.css,file7.css,file8.css]"

fileList[1..-2]
       .split(/, /)
       *.tokenize(/:/)
       .collectEntries { [ it[0], it[1].tokenize(/,/) ] }

should give a result Map as

[
  fileListJs:  ['file1.js', 'file2.js', 'file3.js'], 
  fileListHtml:['file4.html', 'file5.html', 'file6.html'], 
  fileListCss: ['file6.css', 'file7.css', 'file8.css']
]

Upvotes: 1

Related Questions