从Jenkins Pipeline中的Groovy变量创建JSON字符串 [英] Create JSON strings from Groovy variables in Jenkins Pipeline
本文介绍了从Jenkins Pipeline中的Groovy变量创建JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在Groovy中创建此JSON文件.
我尝试了许多尝试(JsonOutput.toJson()
/JsonSlurper.parseText()
)都失败了.
I have to create this JSON file in Groovy.
I have try many things (JsonOutput.toJson()
/ JsonSlurper.parseText()
) unsuccessfully.
{
"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
}
]
}
]
}
这是用于将Jenkins构建消息发布到Slack.
This is for posting a Jenkins build message to Slack.
推荐答案
JSON 是一种格式它使用人类可读的文本来传输由属性-值对和数组数据类型组成的数据对象. 因此,通常json是带格式的文本.
JSON is 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.
在groovy json对象中,只是一个映射/数组序列.
In groovy json object is just a sequence of maps/arrays.
使用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}"
}
使用管道解析json
node{
def data = readJSON file:'message2.json'
echo "color: ${data.attachments[0].color}"
}
从代码构建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)
}
这篇关于从Jenkins Pipeline中的Groovy变量创建JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文