简体   繁体   English

Groovy 读取 json 文件,添加新键:值并写回 (Jenkins)

[英]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.我想从文件中读取 json 字符串,添加一个新键:值并将其写回文件。 with groovy-script during Jenkins-build.在 Jenkins 构建期间使用 groovy-script。 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 .您可以使用这里描述的函数readJsonwriteJson

Long answer长答案

Jenkins from time to time backs up the status of the pipeline to be able to resume it in case of failure. Jenkins 不时备份管道的状态,以便在出现故障时能够恢复它。 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. NotSerializableException通知您在您的上下文(堆栈或堆)中有一个不可序列化的 object,这会阻止管道被序列化。 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.如果不可能,您可以使用@NonCPS注释使用此类对象的函数,以告诉 Jenkins 在执行该 function 期间不要尝试备份管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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