团队
我正在调用 gerrit 服务器,返回的是我相信的 json。由此,我尝试读取字段,但在第一步本身中出现错误。有什么提示吗?我对 gerrit 的调用并存储其响应是成功的,但进一步阅读它是我的挑战。
输出为
Raw Response: )]}'
{"cherrypick":{"method":"POST","label":"Cherry Pick","title":"Cherry pick change to a different branch","enabled":true},"description":{"method":"PUT","label":"Edit Description","enabled":true},"rebase":{"method":"POST","label":"Rebase","title":"Rebase onto tip of branch or parent change.","enabled":true,"enabled_options":["rebase","rebase_on_behalf_of_uploader"]}}
Also: org.jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 49aaf903-ceee-4e7e-83d8-642316a37b95
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object
The current character read is ')' with an int value of 41
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
)]}'
^
at groovy.json.internal.JsonParserCharArray.decodeValueInternal(JsonParserCharArray.java:206)
at groovy.json.internal.JsonParserCharArray.decodeValue(JsonParserCharArray.java:157)
我的詹金斯文件是
stages {
stage('Read Json From Gerrit') {
steps {
script {
def response = sh(
script: "curl -u ${GERRIT_HTTP_USR}:${GERRIT_HTTP_PSW} -s '$GERRIT_API_URL_CHANGES/$GERRIT_CHANGE_NUMBER/revisions/$GERRIT_PATCHSET_REVISION/actions'",
returnStdout: true
).trim()
echo "Raw Response: ${response}"
def json = new JsonSlurper().parseText(response)
我只想看看启用是否为真?这个
"enabled":true
您遇到的错误是由于 JSON 响应开头的额外字符造成的:
)]}'
。这是处理 JSONP 响应或包装 JSON 响应的某些 API 时的常见问题。
要解决此问题,您需要在解析 JSON 之前删除不需要的字符。修改方法如下:
import groovy.json.JsonSlurper
stages {
stage('Read Json From Gerrit') {
steps {
script {
def response = sh(
script: "curl -u ${GERRIT_HTTP_USR}:${GERRIT_HTTP_PSW} -s
'$GERRIT_API_URL_CHANGES/$GERRIT_CHANGE_NUMBER/revisions/$GERRIT_PATCHSET_REVISION/actions'",
returnStdout: true
).trim()
echo "Raw Response: ${response}"
// Remove the unwanted characters at the start
def jsonResponse = response.replaceAll(/^\)\]}'.*/, '')
// Parse the cleaned JSON response
def json = new JsonSlurper().parseText(jsonResponse)
// Check if 'enabled' is true
def isEnabled = json.rebase?.enabled
echo "Is Enabled: ${isEnabled}"
}
}
}
}