![](/img/trans.png)
[英]Convert a JSON style String to a map Groovy in Jenkinsfile
[英]Jenkinsfile - JsonSlurper returning a string instead of a map
所以我正在嘗試一個嵌入了 config.json 文件的 CI 構建。
config.json
{
"some_collection": [
{ "foo": "bar" }
]
}
我的詹金斯檔案:
import groovy.json.JsonSlurper
node {
bootstrap()
test()
}
def bootstrap() {
stage('bootstrap') {
git([url: "git@github.com:my-user/my-jenkinsfile-repo.git"])
}
}
def test() {
def config = getConfig()
echo "${config}"
echo "${config.class}"
}
@NonCPS
def getConfig() {
new JsonSlurper().parseText(readFile("./config.json")))
}
配置對象的回顯顯示文件中的 json,並且 config.class 表示是一個普通的舊字符串。 我期待代碼將返回地圖。
我已經嘗試過 JsonSlurper 和 JsonSluperClassic,我也嘗試了我能想到的所有方法來重組代碼以使其更加明確,但我的想法已經用完了。
編輯:我嘗試添加一些強類型:
def getConfig() {
JsonSlurper parser = new groovy.json.JsonSlurper()
def json = readFile("./config.json")
Map parsedJson = parser.parseText(json)
return parsedJson
}
這仍然導致 config.class 作為字符串返回
在 Jenkins 中使用默認庫處理 JSON 是一團糟。 只需使用 Pipeline Utility Steps Plugin 中的readJSON
步驟即可。 https://github.com/jenkinsci/pipeline-utility-steps-plugin/blob/master/docs/STEPS.md
您可以使用new File(filename)
獲取config.json
的內容並將其傳遞給parse()
方法。
你可以只使用:
def getConfig() {
def pjson = new groovy.json.JsonSlurper().parse(new File('./config.json'))
assert pjson instanceof Map
pjson
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.