Create JSON strings from Groovy variables in Jenkins Pipeline

groovy iterate json array
jenkins pipeline write json
groovy json get value by key
groovy script to loop through json object
groovy update json value
jenkins pipeline findfiles
jenkins pipeline write properties file
groovy parse json from url

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

         "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>",
               "value":"This is much easier than I thought it would be.",

This is for posting a Jenkins build message to Slack.

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

    def json = readFile(file:'message2.json')
    def data = new JsonSlurperClassic().parseText(json)
    echo "color: ${data.attachments[0].color}"

parsing json using pipeline

    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
    //to create json declare a sequence of maps/arrays in groovy
    //here is the data according to your sample
    def data = [
                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)


Create JSON strings from Groovy variables in Jenkins Pipeline , If we have JSON string in a Groovy variable we can parse it to become a Groovy In order to write a JSON file, you need to create the JSON string (either as a  Jenkinsfile pipeline construct JSON object and write to file. jenkins groovy jenkins-pipeline. Create JSON strings from Groovy variables in Jenkins Pipeline.

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.

Parsing and producing JSON, JsonSlurper is a class that parses JSON text or reader content into Groovy data parsing of the given JSON String it tries as hard as possible to avoid creating  Solved: I have setup a test pipeline and deployment pipeline. 2020-05-20 json parsing jenkins jenkins-pipeline jenkins-groovy. I am trying to create a Jenkins pipeline to install package dependencies and my code looks like this: def data = readJSON file:'sfdx-project. Integration: Codeship. Any existing config in any GoCD server will remain valid.

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)

Groovy: JSON - reading and writing, Then, in our Jenkinsfile, we proceed to load the script and use the function to process JSON Another way to create JSON from Groovy is to use JsonBuilder or If we have JSON string in a Groovy variable we can parse it to become a  Wrapping sh step with the Groovy string is only needed when you capture command’s output in the environment block of the declarative pipeline. If you don’t do it that way, the pipeline syntax validation fails instantly, saying that it expects string value on the right side of the assignment.

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


Pipeline Utility Steps, JsonSlurper. We use this Groovy helper class to parse JSON strings. We need to create a new instance of JsonSlurper and call the JsonSlurper. The parsed JSON response is now stored in a variable called parsedJson . This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings. Syntax Static string JsonOutput.toJson(datatype obj) Parameters − The parameters can be an object of a datatype – Number, Boolean, character,String, Date, Map, closure etc. Return type − The return type is a json string. Example

Groovy - JSON, Environment variables are accessible from Groovy code as env. However any variables set this way are global to the Pipeline build. a string representing the fully qualified Cause class and returns a JSON array of build causes filtered by  how to use both Groovy-defined and OS system variable in a multi-line shell script within Jenkins Groovy 1 Mix and match shell variables with groovy variables in Jenkinsfile

Groovy json, This Groovy tutorial for Jenkins will show you how to use Apache Groovy script to build a Jenkins pipeline. Groovy is suitable It has seamless integration with all existing Java objects and libraries. Groovy is Java float, String, etc. Basically it's the same as Java: defining variable without specifying a type. Is an automated expression of your process for getting software from version control to your customers Declarative Scripted Jenkins Pipeline 7. Further, a Groovy String enclosed by triple quotes may span multiple lines. You can also convert any of the YAML examples to JSON and feed that to JJB. Check the Jenkins log for more details about the job.

The Simple Way to Parse JSON Responses Using Groovy and , Create JSON strings from Groovy variables in Jenkins Pipeline (3) I have to create this JSON file in Groovy. I have try many things ( JsonOutput.toJson() / JsonSlurper.parseText() ) unsuccessfully.