简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM