从Jenkins管道上的http请求中提取JSON响应

问题描述

我正在使用jenkins为我的应用创建配置项

以下是我在构建应用后调用的另一个脚本

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

上面的脚本将返回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")

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...