该笔记将记录: 将数据转化为 JSON 字符串并写入文件 以及 从文件中读取 JSON 字符串并解析为对象 的方法

有关其他 JSON 相关操作(比如禁止 Unicode 转义),参考 Apache Groovy/JSON 笔记

读取:从文件中读取 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)

「Jenkins Pipeline」- SSH
「Jenkins Pipeline」- 执行 Shell 命令
「Jenkins Pipeline」- 连接 MySQL 数据库
「Jenkins Pipeline」- Generic Webhook Trigger
「Jenkins Pipeline」- 发送 HTTP 请求
「Jenkins Pipeline」- 配置多版本NodeJS构建环境
「Jenkins Pipeline」- 常见问题处理
「Jenkins Pipeline」- 集成 Selenium 测试

Create JSON strings from Groovy variables in Jenkins Pipeline
Parsing and producing JSON