You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:30:05