本文介绍了在 Jenkins Pipeline 中从 Groovy 变量创建 JSON 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 Groovy 中创建这个 JSON 文件.我尝试了很多事情(JsonOutput.toJson()/JsonSlurper.parseText())都没有成功.

I have to create this JSON file in Groovy.I have try many things (JsonOutput.toJson() / JsonSlurper.parseText()) unsuccessfully.

{
   "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
            }
         ]
      }
   ]
}

这是为了向 Slack 发布 Jenkins 构建消息.

This is for posting a Jenkins build message to Slack.

推荐答案

JSON 是一种格式它使用人类可读的文本来传输由属性值对和数组数据类型组成的数据对象.所以,一般情况下 json 是一个格式化的文本.

JSON is a format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types.So, in general json is a formatted text.

在 groovy json 对象中只是一个映射/数组序列.

In groovy json object is just a sequence of maps/arrays.

使用 JsonSlurperClassic 解析 json

//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

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

从代码构建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)

}

这篇关于在 Jenkins Pipeline 中从 Groovy 变量创建 JSON 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:12