# 2020/09/17 #「Jenkins Pipeline」- 常用 JSON 操作

该笔记将记录:将数据转化为 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)

参考文献

K4NZ / 常用 JSON 操作
Create JSON strings from Groovy variables in Jenkins Pipeline
Parsing and producing JSON

猜你喜欢

转载自blog.csdn.net/u013670453/article/details/108676896
今日推荐