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

Groovy Jenkins递归遍历嵌套Map报错及期望键值输出需求

Groovy递归遍历嵌套Map的问题解决

问题根源

  1. 语法错误:Groovy里Map的键如果包含连字符(比如on-profile),不能直接写on-profile:xxx,必须用引号把键包起来,不然会被当成表达式解析,触发illegal colon错误。
  2. 函数逻辑失效:你写的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:13:20