JSON是一种使用人类可读文本传输由属性值对和数组数据类型组成的数据对象的格式。 所以,一般来说json是一个格式化的文本。
在groovy json对象只是一个映射/数组序列。
解析使用管道从代码
node{
def data = readJSON file:'message2.json'
echo "color: ${data.attachments[0].color}"
}
建筑JSON使用JsonSlurperClassic
//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 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)
}
问题的标题问你解析,并问题本身你问有关创建json文件。你能否澄清你想要做什么? – daggett
@daggett我想将这些JSON对象创建为一个常规变量。 –