首页 > 解决方案 > 如何在 groovy 中解析 JSON 数组

问题描述

我有以下数组,我想访问我的 Jenkinsfile 中的键值对。

[
    {
        "AppName": "app1",
        "version": "1.0.0.1"
    },
    {
        "AppName": "app2",
        "version": "1.0.0.2"
    },
    {
        "AppName": "app3",
        "version": "1.0.0.3"
    }
]

我想获取应用程序名称和版本,并通过 curl 命令从我的存储库下载应用程序。我已经尝试过这个解决方案但不起作用。我在 jenkins 控制台上收到错误消息hudson.remoting.ProxyException: net.sf.json.JSONException: Invalid JSON String。我不知道我还做错了什么。我的计划是为阵列中的每个应用程序名称和版本下载具有以下 URL 的应用程序。

sh "curl https://example.com/${AppName}/${version}/${AppName}-${version}.zip -O"

这是我的詹金斯文件

node { 
    stage ('checkou') {
        checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'SparseCheckoutPaths', sparseCheckoutPaths: [[path: 'projectA/testProjectfile.json']]]], submoduleCfg: [], userRemoteConfigs: [[url: 'ssh://myrepository.com/apps/projectA.git']]])
    }
    stage ('read file') {
        def data = readFile(file: "${WORKSPACE}/projectA/testProjectfile.json")
        echo "$data"
        def list = new JsonSlurper().parseText( data )
        list.each { println it }
        
    }
    
    stage ('download app') {
        sh "curl https://example.com/${AppName}/${version}/${AppName}-${version}.zip -O"
    
    }
}

那是我的 Jenkinsfile,这是我运行管道时的日志

[Pipeline] echo
[
    {
      "AppName": "app1",
      "version": "1.0.0.1"
    },
    {
      "AppName": "app2",
      "version": "1.0.0.2"
    },
    {
      "AppName": "app3",
      "version": "1.0.0.3"
    }
]
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
hudson.remoting.ProxyException: net.sf.json.JSONException: Invalid JSON String
    at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:143)
    at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:103)
    at net.sf.json.groovy.JsonSlurper.parseText(JsonSlurper.java:80)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)

标签: jenkinsgroovyjenkins-pipelinejenkins-groovy

解决方案


推荐阅读