如何在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
相关产品推荐
相关产品推荐

