Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkinsfile pipeline construct JSON object and write to file

I would like to construct a JSON object and write the content to file.

Originally I was inspired by this and tried:

def data = [
        a:"test: ${myVar}"
    ]
    writeJSON(file: 'message1.json', json: data)

But this failed with:

Could not instantiate {file=message1.json, json={a=test}} for WriteJSONStep(file: String, json: JSON{}, pretty?: int): java.lang.UnsupportedOperationException: must specify $class with an implementation of interface net.sf.json.JSON

So next I tried:

def data = readJSON text: '{}'
data.a = "test: ${myVar}"
writeJSON(file: 'message1.json', json: data, pretty: 4)

Now the build passes, but the content of the file looks like:

{
     "a":     {

        "bytes":         [

            114,

            101,

            108,

            101,

            97,

            115,

            101

            50

        ],

        "strings":         [

            "test: ",

            ""

        ],

        "valueCount": 1,

        "values": ["v1.0.2"]

    }
}

Whereas my intention was {"a": "test: v1.0.2"}

My end goal is that I want to dynamically construct a JSON object, set some properties with some dynamic data and then write the JSON file.

Is there some syntax that can be used to assign the values as strings, rather than some bytes.

like image 579
David Avatar asked Nov 16 '18 11:11

David


People also ask

How do I write to a file in Jenkins pipeline?

In the first stage we create a variable called data that holds some text and the we use the writeFile function to write it out to a file. Then we execute ls as an external program using sh. In the second stage we use the readFile function to read in the content of the file.

Is Jenkinsfile a text file?

As discussed in the Defining a Pipeline in SCM, a Jenkinsfile is a text file that contains the definition of a Jenkins Pipeline and is checked into source control.

What does checkout SCM do in Jenkinsfile?

Since the Jenkinsfile is pulled from the source repo, “checkout scm” provides an easy way to access right revision of source code. Here, “checkout” variable will checkout the source from source repo and it accepts the scm variable which instructs the checkout step to clone the specific revision.


1 Answers

It seems one solution to this is changing the code that adds to the map to specify as String:

def data = readJSON text: '{}'
data.a = "test: ${myVar}" as String
writeJSON(file: 'message1.json', json: data, pretty: 4)
like image 68
David Avatar answered Oct 31 '22 17:10

David