我有一個 Jenkins decalarative 管道,我通過 cURL 呼叫一些 URL,它回傳 JSON 回應。如何在變數中捕獲該 JSON?
已經嘗試了下面的代碼,但它回傳了整個帶有路徑和命令的東西以及回應
environment {
token = bat(returnStdout: true, script: 'curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"username\\" : \\"user\\",\\"password\\" : \\"pwd\\"}"').trim()
}
JSON 回應
C:\ProgramData\Jenkins\.jenkins\workspace\publish-api>curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\"username\" : \"ap-1\",\"password\" : \"Ap5\"}"
{
"access_token": "axxxx-5ca2-48eb-9eb3-173c44a811",
"token_type": "bearer",
"redirectUrl": "/home/"
}
uj5u.com熱心網友回復:
您可以使用readJson方法來獲得您想要的結果。您不必在環境塊中呼叫它。
stage('Curl') {
steps {
script {
def cUrlResponse = bat(returnStdout: true, script: '@curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"${env.username}\\" : \\"user\\",\\"${env.password}\\" : \\"pwd\\"}"').trim()
def responseJson = readJSON text: cUrlResponse
def accessToken = responseJson.access_token
def tokenType = responseJson.token_type
// do other stuff with the variables
}
}
}
要從輸出中排除 curl 命令,請按照檔案中的說明在腳本前添加 @。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/510157.html
