Create Json Strings from Groovy Variables in Jenkins Pipeline

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]: < out Slack message attachments>",
         "pretext":"New open task [Urgent]: < out Slack message attachments>",
         "color":"#D00000",
         "fields":[
            {
               "title":"Notes",
               "value":"This is much easier than I thought it would be.",
               "short":false
            }
         ]
      }
   ]
}

This is for posting a Jenkins build message to Slack.

2

4 Answers

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.

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

parsing json using 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}"
}

parsing json using pipeline

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

building json from code and write it to file

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]: < out Slack message attachments>",
                pretext : "New open task [Urgent]: < 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)

}
6

Found this question while I was trying to do something (I believed) should be simple to do, but wasn't addressed by the other answer. If you already have the JSON loaded as a string inside a variable, how do you convert it to a native object? Obviously you could do new JsonSlurperClassic().parseText(json) as the other answer suggests, but there is a native way in Jenkins to do this:

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

Hope this helps someone.

Edit: As explained in the comments "native" isn't quite accurate.

4

If you are stucked on an installation using sandboxes and Jenkins Script Security plugin with no possibility to add whitelisted classes/methods, the only way I found is the following :

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)
}

This will return value of the "version" from the jsonFile file:

def getVersion(jsonFile){

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

  return version

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest