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

如何在Jenkinsfile中用Groovy合并列表与JSON对象数组

在Jenkinsfile中用Groovy实现给JSON对象数组添加Account字段

实现代码示例

pipeline {
    agent any
    stages {
        stage('Process JSON Array') {
            steps {
                script {
                    // 定义原始数据
                    def accountList = [1, 2, 3, 4, 5, 6]
                    def fullList = [
                        ["Key": "CI", "Value": "SERVICES"],
                        ["Key": "CI", "Value": ""]
                    ]

                    // 为每个JSON对象添加Account字段
                    fullList.eachWithIndex { item, index ->
                        item.Account = accountList[index]
                    }

                    // 输出处理结果
                    println "处理后的数组:"
                    println fullList
                }
            }
        }
    }
}

代码说明

  • Groovy中可以直接用Map类型表示JSON对象,因此无需额外的JSON解析库,直接操作即可。
  • 使用eachWithIndex遍历fullList,同时获取元素的索引,从accountList中取出对应位置的值,赋值给当前对象的Account字段。
  • 运行后fullList的结果会是:
    [
        [Key:CI, Value:SERVICES, Account:1],
        [Key:CI, Value:, Account:2]
    ]
    

边界情况处理

如果fullList的长度大于accountList,为了避免索引越界异常,可以添加判断逻辑:

fullList.eachWithIndex { item, index ->
    item.Account = index < accountList.size() ? accountList[index] : null
}

内容的提问来源于stack exchange,提问作者Yash Kamdar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:11:58