在 Jenkins Pipeline 中从 Groovy 变量创建 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44707265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create JSON strings from Groovy variables in Jenkins Pipeline
提问by Mr_DeLeTeD
I have to create this JSON file in Groovy.
I have try many things (JsonOutput.toJson()/ JsonSlurper.parseText()) unsuccessfully.
我必须在 Groovy 中创建这个 JSON 文件。我尝试了很多事情(JsonOutput.toJson()/ JsonSlurper.parseText())都没有成功。
{
"attachments":[
{
"fallback":"New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
"pretext":"New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
"color":"#D00000",
"fields":[
{
"title":"Notes",
"value":"This is much easier than I thought it would be.",
"short":false
}
]
}
]
}
This is for posting a Jenkins build message to Slack.
这是用于向 Slack 发布 Jenkins 构建消息。
回答by daggett
JSONis a format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types. So, in general json is a formatted text.
JSON是一种格式,它使用人类可读的文本来传输由属性值对和数组数据类型组成的数据对象。所以,一般情况下 json 是一个格式化的文本。
In groovy json object is just a sequence of maps/arrays.
在 groovy json 对象中只是一个映射/数组序列。
parsing json using JsonSlurperClassic
使用 JsonSlurperClassic 解析 json
//use JsonSlurperClassic because it produces HashMap that could be serialized by pipeline
import groovy.json.JsonSlurperClassic
node{
def json = readFile(file:'message2.json')
def data = new JsonSlurperClassic().parseText(json)
echo "color: ${data.attachments[0].color}"
}
parsing json using pipeline
使用管道解析json
node{
def data = readJSON file:'message2.json'
echo "color: ${data.attachments[0].color}"
}
building json from code and write it to file
从代码构建json并将其写入文件
import groovy.json.JsonOutput
node{
//to create json declare a sequence of maps/arrays in groovy
//here is the data according to your sample
def data = [
attachments:[
[
fallback: "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
pretext : "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
color : "#D00000",
fields :[
[
title: "Notes",
value: "This is much easier than I thought it would be.",
short: false
]
]
]
]
]
//two alternatives to write
//native pipeline step:
writeJSON(file: 'message1.json', json: data)
//but if writeJSON not supported by your version:
//convert maps/arrays to json formatted string
def json = JsonOutput.toJson(data)
//if you need pretty print (multiline) json
json = JsonOutput.prettyPrint(json)
//put string into the file:
writeFile(file:'message2.json', text: json)
}
回答by mrfred
Found this question while I was trying to do something (I believed) should be simple to do, but wasn't addressed by the other answer. If you already have the JSON loaded as a string inside a variable, how do you convert it to a native object? Obviously you could do new JsonSlurperClassic().parseText(json)
as the other answer suggests, but there is a native way in Jenkins to do this:
在我尝试做某事时发现这个问题(我认为)应该很简单,但其他答案没有解决。如果您已经将 JSON 作为字符串加载到变量中,您如何将其转换为本地对象?显然,您可以new JsonSlurperClassic().parseText(json)
按照另一个答案的建议进行操作,但是 Jenkins 有一种本地方式可以做到这一点:
node () {
def myJson = '{"version":"1.0.0"}';
def myObject = readJSON text: myJson;
echo myObject.version;
}
Hope this helps someone.
希望这可以帮助某人。
Edit: As explained in the comments "native" isn't quite accurate.
编辑:正如评论中所解释的,“本机”不太准确。
回答by Nicolas Vuillamy
If you are stucked on an installation using sandboxes and Jenkins Script Security plugin with no possibility to add whitelisted classes/methods, the only way I found is the following :
如果您坚持使用沙箱和 Jenkins 脚本安全插件进行安装而无法添加列入白名单的类/方法,我发现的唯一方法如下:
def slackSendOnRestrictedContext(params) {
if (params.attachments != null) {
/* Soooo ugly but no other choice with restrictions of
Jenkins Script Pipeline Security plugin ^^ */
def paramsAsJson = JsonOutput.toJson(params)
def paramsAsJsonFromReadJson = readJSON text: paramsAsJson
params.attachments = paramsAsJsonFromReadJson.attachments.toString()
}
slackSend (params)
}
回答by Nikola Reljin
This will return value of the "version" from the jsonFile file:
这将从 jsonFile 文件返回“版本”的值:
def getVersion(jsonFile){
def fileContent = readFile "${jsonFile}"
Map jsonContent = (Map) new JsonSlurper().parseText(fileContent)
version = jsonContent.get("version")
return version
}

