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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With