【问题标题】:Create JSON strings from Groovy variables in Jenkins Pipeline从 Jenkins Pipeline 中的 Groovy 变量创建 JSON 字符串
【发布时间】:2017-11-26 04:44:19
【问题描述】:

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

{
   "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。

【问题讨论】:

  • 在您询问解析的问题标题中,以及您询问有关创建 json 文件的问题本身。你能澄清一下你想要/尝试做什么吗?
  • @daggett 我想将这些 JSON 对象创建为一个 groovy 变量。

标签: json jenkins groovy jenkins-pipeline


【解决方案1】:

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

在 groovy 中,json 对象只是一系列映射/数组。

使用 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)

}

【讨论】:

  • 我正在尝试这样做。我收到“错误:org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:脚本不允许使用新的 groovy.json.JsonSlurperClassic”我错过了什么?
  • 这在最新版本的詹金斯 (2.138.3) 中对我不起作用。我在 writeJSON 步骤中遇到问题:WriteJSONStep(file: String, json: JSON{}, pretty?: int): java.lang.UnsupportedOperationException: must specify $class with an implementation of interface net.sf.json.JSON更多上下文:stackoverflow.com/questions/53337109/…
  • @DavidGoate,在这种情况下不要使用writeFile,而是代码中的最后三个命令:JsonOutput.toJsonJsonOutput.prettyPrintwriteFile
  • 感谢您提供有关 JsonSlurperClassic 的信息。我尝试了 JsonSlurper,但如果多次调用“new”,即使有 NonCPS 注释,它也会导致 NotSerializableException。
【解决方案2】:

在我尝试做某事(我认为)应该很容易做的时候发现这个问题,但其他答案没有解决。如果您已经将 JSON 作为字符串加载到变量中,那么如何将其转换为本机对象?显然你可以像其他答案所暗示的那样做new JsonSlurperClassic().parseText(json) ,但是詹金斯有一种本地方式可以做到这一点:

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

希望这对某人有所帮助。

编辑:正如 cmets 中所解释的,“本机”并不十分准确。

【讨论】:

  • 好电话,虽然这不是很原生,但它需要pipeline utility steps plugin。一个优秀的插件,可以使用。 Full docs here
  • 如果我们有一个字符串 '[ {"version":"1.0.0"} , {"version":"2.0.0"}]' 如何读取数组?
  • 您将需要 Pipeline Utility Steps 插件,如 here 所述
  • 这解决了与 OP 问题相反的问题:如何从对象转到 json 字符串
【解决方案3】:

这将从 jsonFile 文件返回“版本”的值:

def getVersion(jsonFile){

  def fileContent = readFile "${jsonFile}"
  Map jsonContent = (Map) new JsonSlurper().parseText(fileContent)
  version = jsonContent.get("version")

  return version

}

【讨论】:

    【解决方案4】:

    如果您被困在使用沙盒和 Jenkins 脚本安全插件的安装上,而无法添加列入白名单的类/方法,我发现的唯一方法如下:

    def slackSendOnRestrictedContext(params) {
    
        if (params.attachments != null) {
            /* Soooo ugly but no other choice with restrictions of
               Jenkins Script Pipeline Security plugin ^^ */
            def paramsAsJson = JsonOutput.toJson(params)
            def paramsAsJsonFromReadJson = readJSON text: paramsAsJson
            params.attachments = paramsAsJsonFromReadJson.attachments.toString()
        }
    
        slackSend (params)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 2012-05-11
      • 2016-12-21
      相关资源
      最近更新 更多