如何在Groovy中提取Map的所有嵌套键值对(Jenkins适用)
Groovy遍历嵌套Map生成完整键路径
实现思路
通过递归遍历Map的每个键值对:
- 若值为嵌套Map,则继续递归,同时拼接当前键到路径中
- 若值为普通类型,则输出完整路径(用冒号分隔所有前置键)+ 键 + 值的格式
完整代码实现
def printFullPaths(Map map, String currentPath = "") { map.each { key, value -> def newPath = currentPath ? "${currentPath}:${key}" : key.toString() if (value instanceof Map) { printFullPaths(value, newPath) } else { println "${newPath}=${value}" } } } // 示例输入Map def inputMap = [ a: [ b: [c:1, d:2, e:3], r: [p:4], q:5 ] ] // 调用方法生成结果 printFullPaths(inputMap)
运行结果
a:b:c=1 a:b:d=2 a:b:e=3 a:r:p=4 a:q=5
适配动态字符串输入
如果你的输入是字符串形式的Map(比如从Jenkins参数传入的非标准格式字符串),可以先将字符串转为Groovy可识别的Map对象:
def inputStr = 'a={b={c=1,d=2,e=3},r={p=4},q=5}' // 替换字符串中的=为:,符合Groovy Map语法 def formattedStr = inputStr.replaceAll('=', ':') // 解析字符串为Map对象 def inputMap = new GroovyShell().evaluate("[$formattedStr]") printFullPaths(inputMap)
内容的提问来源于stack exchange,提问作者Amit
相关产品推荐
相关产品推荐

