从 jenkins 管道上的 http 请求中提取 json 响应

Extracting json response from http request on jenkins pipeline

我正在使用 jenkins

为我的应用创建 CI

下面是我在构建应用程序后调用的附加脚本

script{            
      sh 'curl -X POST -H "Authorization:test "https://api/upload" -F "file=@path"'
     }
   

上面的脚本会return json响应,我如何从json中提取ID字段并将其存储在变量中?

尝试一下,尚未测试。

script{            
      sh 'ID=$(curl -X POST -H "Authorization:test "https://api/upload" -F "file=@path")'
      sh 'curl -X POST -H "Authorization:test" -F app_id=$ID  -H "content-type: multipart/form-data" https://api/tasks'
     }

您可以在 returnStdout:true 的帮助下将输出分配给变量。

pipeline {
  agent any

  stages {
    stage('test') {
      steps {
        script{            
          def output = sh returnStdout:true, script: '''
            curl -X POST -H "Authorization:test" \
              "https://api/upload" -F "file=@path"
          '''
          sh """
            curl -X POST -H "Authorization:test" -F app_id=$ID \
              -H "content-type: multipart/form-data" \
              https://api/tasks
          """
        }
      }
    }
  }
}

然后在双引号内替换变量。

这是我从 json 响应中获取 ID 的方法。

def response = sh(script: 'curl -X POST -H "Authorization:test" -H "content-type: multipart/form-data" https://api/upload', returnStdout: true)   
def responseObject = readJSON text: response
def ID = "$responseObject.id"
println("ID:  $ID")