2017-06-22 1334 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/) –