0

While iterating map I am getting error. Followed with the below approach:

How to iterate through all values of a nested map in groovy

def deNull(root) { if (root instanceof List) { root.collect { if (it instanceof Map) { deNull(it) } else if (it instanceof List) { deNull(it) } } def map = [spring:[config:[activate:[on-profile:stage-release]]], test-property:stage] map = deNull(map) println map.inspect()

Error: startup failed: Script1.groovy: 9: illegal colon after argument expression; solution: a complex label expression before a colon must be parenthesized @ line 9, column 48. :[config:[activate:[on-profile:stage-rel ^ 1 error

I want output like below in key value pair. on-profile=stage test-property=stage

Amit
  • 15
  • 3

1 Answers1

0

Some hints:

  • String values in Maps should be put in quotation marks
  • keys in Maps containing special characters like - should also be put in quotation marks.
  • The deNull method from your link iterates through the Map and replaces all the null values. I guess you're aiming to collect all the leaves of your tree.

Maybe that helps:

Map map = [spring:[config:[activate:["on-profile":"stage-release"]]], "test-property":"stage"]
List leaves = traverse(map)
assert leaves as String == "[on-profile=stage-release, test-property=stage]"

def traverse(root){
    if(root in Map){
        root.collectMany { (it.value in Map) ? traverse(it.value) : [it] }
    }else{
        root
    }
}
IWilms
  • 500
  • 3
  • 10
  • Yes correct I am trying to collect all the leaves in key-value pair format. I am reading yaml file and that is dynamic don't know the structure of yaml file. I am implementing rule validator same will executed while running pipeline. – Amit May 12 '23 at 04:12