Groovy Jenkins递归遍历嵌套Map报错及期望键值输出需求
Groovy递归遍历嵌套Map的问题解决
问题根源
- 语法错误:Groovy里Map的键如果包含连字符(比如
on-profile),不能直接写on-profile:xxx,必须用引号把键包起来,不然会被当成表达式解析,触发illegal colon错误。 - 函数逻辑失效:你写的
deNull函数只处理了List类型,完全没处理Map的递归遍历,根本没法把嵌套Map展开成你要的扁平键值对。
修正后的代码
// 递归扁平化嵌套Map,提取所有叶子节点键值对 def flattenMap(Map map, String parentKey = '') { def result = [:] map.each { key, value -> def fullKey = parentKey ? "${parentKey}.${key}" : key if (value instanceof Map) { result.putAll(flattenMap(value, fullKey)) } else { // 按需求把stage-release转为stage,不需要的话可以删掉replace部分 result[key] = value.toString().replace('-release', '') } } return result } // 修正带连字符的键,用引号包裹 def map = [ spring: [ config: [ activate: ['on-profile': 'stage-release'] ] ], 'test-property': 'stage' ] // 处理并输出结果 def flattened = flattenMap(map) flattened.each { key, value -> println "${key}=${value}" }
输出结果
on-profile=stage test-property=stage
内容的提问来源于stack exchange,提问作者Amit
相关产品推荐
相关产品推荐

