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

Jenkins Groovy脚本仅写入首个JSON值至文件问题排查

问题原因及修复方案

你的脚本问题出在直接拼接单个JSON对象的字符串,这样最终得到的是多个独立JSON对象连在一起的非法格式,JsonOutput.prettyPrint处理这种不合法的JSON时,只会解析并保留第一个有效对象,所以最终文件里只有第一条数据。

修复步骤:

  1. 把单个对象的拼接改成收集到列表中
  2. 最后将整个列表转成合法的JSON数组

修复后的完整脚本:

import groovy.json.JsonOutput
def arn = ""
def name = ""
def os = ""
pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                script{
                    def ret = sh(script: 'aws devicefarm list-devices', returnStdout: true)
                    def jsonObj = readJSON text: ret
                    def currentVersion = "13.0"
                    def values = currentVersion.split('\\.')
                    // 用列表存储所有符合条件的对象
                    def deviceList = []
                    
                    for(String item: jsonObj.devices) {
                        os = item.os
                        def osV = os.contains("\\.") ? os : "${os}.0"
                        def osValues = osV.split('\\.')
                        
                        if(values[0].toInteger() <= osValues[0].toInteger()) {
                            name = item.name
                            // 将符合条件的对象添加到列表
                            deviceList.add([
                                name: name,
                                os: os
                            ])
                        }
                    }
                    // 将整个列表转成JSON数组并格式化
                    def json_beauty = JsonOutput.prettyPrint(JsonOutput.toJson(deviceList))
                    writeJSON(file: 'message124.json', json: json_beauty)
                }
            }
        }
    }
}

额外优化点:

  • 用三元运算符简化了osV的赋值逻辑,代码更简洁
  • 去掉了字符串插值里的冗余引号(name: "$name"改成name: name,Groovy会自动处理)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:50:47