「Jenkins Pipeline」- 常用 JSON 操作
更新日期:2020年07月11日
读取:从文件中读取 JSON 字符串,并直接解析为对象
// Parsing json using pipeline
node{
def dataObject = readJSON file: 'message2.json'
echo "color: ${dataObject.attachments[0].color}"
}
读取:从文件中读取 JSON 字符串,并手动解析为对象
从文件中读取 JSON 字符串,然后解析对象:
// Parsing json using JsonSlurperClassic
import groovy.json.JsonSlurperClassic
node{
// 从文件中读取 JSON 字符串
def jsonString = readFile(file: 'message2.json') // '{"k":"1", "n":"2"}'
// 解析 JSON 字符串为对象
def dataObject = new JsonSlurperClassic().parseText(jsonString)
// 从对象中获取参数
echo "color: ${dataObject.k}"
}
保存:将对象直接写入文件,无需先转化为 JSON 字符串
// Building json from code and write it to file
writeJSON(file: 'message1.json', json: dataObject)
保存:将对象转化 JSON 字符串,然后写入文件
import groovy.json.JsonOutput
def jsonString = JsonOutput.toJson(dataObject)
writeFile(file: 'message2.json', text: jsonString) // put string into the file:
// json = JsonOutput.prettyPrint(jsonString)
参考文献