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對象創建爲一個常規變量。 –