2017-06-22 436 views
5

我必須在Groovy中創建這個JSON文件。 我嘗試了很多東西(JsonOutput.toJson()/JsonSlurper.parseText())失敗。Jenkins管道Groovy json解析

{ 
    "attachments":[ 
     { 
     "fallback":"New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>", 
     "pretext":"New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>", 
     "color":"#D00000", 
     "fields":[ 
      { 
       "title":"Notes", 
       "value":"This is much easier than I thought it would be.", 
       "short":false 
      } 
     ] 
     } 
    ] 
} 

這是張貼Jenkins構建消息到Slack。

+0

問題的標題問你解析,並問題本身你問有關創建json文件。你能否澄清你想要做什麼? – daggett

+0

@daggett我想將這些JSON對象創建爲一個常規變量。 –

回答

10

JSON是一種使用人類可讀文本傳輸由屬性值對和數組數據類型組成的數據對象的格式。 所以,一般來說json是一個格式化的文本。

在groovy json對象只是一個映射/數組序列。

解析使用管道從代碼

node{ 
    def data = readJSON file:'message2.json' 
    echo "color: ${data.attachments[0].color}" 
} 

建築JSON使用JsonSlurperClassic

//use JsonSlurperClassic because it produces HashMap that could be serialized by pipeline 
import groovy.json.JsonSlurperClassic 

node{ 
    def json = readFile(file:'message2.json') 
    def data = new JsonSlurperClassic().parseText(json) 
    echo "color: ${data.attachments[0].color}" 
} 

解析JSON JSON並將其寫入到文件

import groovy.json.JsonOutput 
node{ 
    //to create json declare a sequence of maps/arrays in groovy 
    //here is the data according to your sample 
    def data = [ 
     attachments:[ 
      [ 
       fallback: "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>", 
       pretext : "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>", 
       color : "#D00000", 
       fields :[ 
        [ 
         title: "Notes", 
         value: "This is much easier than I thought it would be.", 
         short: false 
        ] 
       ] 
      ] 
     ] 
    ] 
    //two alternatives to write 

    //native pipeline step: 
    writeJSON(file: 'message1.json', json: data) 

    //but if writeJSON not supported by your version: 
    //convert maps/arrays to json formatted string 
    def json = JsonOutput.toJson(data) 
    //if you need pretty print (multiline) json 
    json = JsonOutput.prettyPrint(json) 

    //put string into the file: 
    writeFile(file:'message2.json', text: json) 

} 
5

在我試圖做某件事的時候發現了這個問題(我相信)應該很簡單,但沒有被其他答案解決。如果已經將JSON作爲字符串加載到變量中,那麼如何將其轉換爲本地對象?很明顯,你可以做new JsonSlurperClassic().parseText(json) 爲對方的回答暗示,但在詹金斯原生的方式來做到這一點:

node() { 
    def myJson = '{"version":"1.0.0"}'; 
    def myObject = readJSON text: myJson; 
    echo myObject.version; 
} 

希望這可以幫助別人。

編輯:正如評論中所說「本地」不是很準確。

+2

良好的調用,雖然這不是很原生,但它需要[管道實用步驟插件](https://plugins.jenkins.io/pipeline-utility-steps)。一個很好的插件可供使用。 [完整文檔](https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/) –