Maximilian
Maximilian

Reputation: 31

Groovy read json-file, add new key : value and write back (Jenkins)

I want to read a json string out of a file, add a new key : value and write it back to the file. with groovy-script during Jenkins-build. file:

{"key1": "value1", "key2": "value2"}

I tried the following:

def setValue(String filepath, String key, value){
    String fileContent = readFile(filepath)
 
    Map jsonContent = (Map) new JsonSlurper().parseText(fileContent)
    jsonContent.put("${key}", "${value}")
 
    writeFile(file: filepath, text: JsonOutput.toJson(jsonContent))
}

but getting the following error:

exception: class java.io.NotSerializableException
[Pipeline] echo
message: groovy.json.internal.LazyMap

Upvotes: 0

Views: 4078

Answers (1)

Bernard
Bernard

Reputation: 375

Quick answer

You can use the functions readJson and writeJson as described here.

Long answer

Jenkins from time to time backs up the status of the pipeline to be able to resume it in case of failure. During this backup step, it tries to serialize every element in the current context of the pipeline. NotSerializableException notifies you that you have a not serializable object in your context (stack or heap) which prevents the pipeline from being serialized. Therefore try to only use serializable objects. If it is not possible, you can annotate functions that use such objects with @NonCPS to tell Jenkins not to atempt to back up the pipeline during the execution of that function.

Upvotes: 1

Related Questions