从Jenkins管道中的Groovy变量创建JSON字符串

从Jenkins管道中的Groovy变量创建JSON字符串,json,jenkins,groovy,jenkins-pipeline,Json,Jenkins,Groovy,Jenkins Pipeline,我必须在Groovy中创建这个JSON文件。 我尝试了很多事情(JsonOutput.toJson()/JsonSlurper.parseText())都没有成功 { "attachments":[ { "fallback":"New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>", "pretext":"New open t

我必须在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
            }
         ]
      }
   ]
}
{
“附件”:[
{
“回退”:“新打开的任务[紧急]:”,
“借口”:“新打开的任务[紧急]:”,
“颜色”:“D00000”,
“字段”:[
{
“标题”:“注释”,
“价值”:“这比我想象的要容易得多。”,
“短”:假
}
]
}
]
}
这是用于向Slack发布Jenkins构建消息。

是一种使用人类可读文本传输由属性-值对和数组数据类型组成的数据对象的格式。 因此,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}"
}
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)

}
从代码构建json并将其写入文件

node{
    def data = readJSON file:'message2.json'
    echo "color: ${data.attachments[0].color}"
}
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)

}
import groovy.json.JsonOutput
节点{
//要创建json,请在groovy中声明映射/数组序列
//这是根据你的样品提供的数据
def数据=[
附件:[
[
回退:“新打开的任务[紧急]:”,
借口:“新的开放任务[紧急]:”,
颜色:“D00000”,
字段:[
[
标题:“注释”,
价值观:“这比我想象的要容易得多。”,
短:错
]
]
]
]
]
//两种写作选择
//本机管道步骤:
writeJSON(文件:'message1.json',json:data)
//但如果您的版本不支持writeJSON:
//将映射/数组转换为json格式的字符串
def json=JsonOutput.toJson(数据)
//如果您需要漂亮的打印(多行)json
json=JsonOutput.prettyPrint(json)
//将字符串放入文件:
writeFile(文件:'message2.json',文本:json)
}

在我尝试做一些(我认为)应该简单的事情时发现了这个问题,但另一个答案没有解决。如果已经将JSON作为字符串加载到变量中,如何将其转换为本机对象?显然,您可以执行
newjsonslurperclassic().parseText(json)
正如另一个答案所示,但詹金斯有一种天生的方法:

node () {
  def myJson = '{"version":"1.0.0"}';
  def myObject = readJSON text: myJson;
  echo myObject.version;
}
希望这对别人有帮助


编辑:如注释中所述,“本机”不太准确。

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

def getVersion(jsonFile){

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

  return version

}

如果您在使用沙盒和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)
}

在问题的标题中,您询问有关解析的问题,在问题本身中,您询问有关创建json文件的问题。请您澄清一下您想要/尝试做什么。@daggett我想将这些JSON对象创建到groovy变量中。这是一个很好的调用,虽然它不是完全本地的,但需要。一个很好的插件可以使用。如果我们有一个字符串“[{”version:“1.0.0”},{”version:“2.0.0”}]”如何读取数组?您将需要管道实用程序步骤插件,如前所述,这解决了OPs的相反问题:如何从对象转到json字符串我正在尝试这样做。我得到“ERROR:org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:Scripts不允许使用新的groovy.json.JsonSlurperClassic”我缺少什么?这在最新版本的jenkins(2.138.3)中不适用。我在writeJSON步骤中遇到了一个问题:
WriteJSONStep(文件:String,json:json{},pretty?:int):java.lang.UnsupportedOperationException:必须使用接口net.sf.json.json的实现指定$class
更多上下文:@DavidGoate,在这种情况下不要使用
writeFile
,但是代码中的最后三个命令:
JsonOutput.toJson
JsonOutput.prettyPrint
writeFile
。感谢您提供有关JsonSlurperClassic的信息。我尝试了JsonSlurper,但如果多次调用“new”,则会导致NotSerializableException,即使不考虑NonCPS注释。