該筆記將記錄:將數據轉化為 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