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


相关文章:

  • 2022-12-23
  • 2021-08-19
  • 2021-12-31
  • 2021-12-20
  • 2022-12-23
猜你喜欢
  • 2021-06-03
  • 2021-09-09
  • 2022-01-24
  • 2021-07-21
  • 2021-08-29
  • 2022-02-25
  • 2021-12-03
相关资源
相似解决方案