Groovy 读取 JSON 文件,添加新的键值对并写回 (Jenkins)

huangapple go评论98阅读模式
英文:

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

问题

Here's the translated code snippet without the translation of the error message:

我想要从文件中读取一个JSON字符串,添加一个新的键值对,然后将其写回文件中,使用Groovy脚本在Jenkins构建过程中
文件:
```json
{"key1": "value1", "key2": "value2"}

我尝试了以下方法:

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))
}

这是您请求的代码翻译部分。如果您需要更多帮助,请随时提出。

<details>
<summary>英文:</summary>

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:
```json
{&quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value2&quot;}

I tried the following:

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

but getting the following error:

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

答案1

得分: 1

您可以使用描述在这里readJsonwriteJson函数。

Jenkins不时将流水线的状态备份,以便在发生故障时能够恢复它。在此备份步骤期间,它尝试对流水线当前上下文中的每个元素进行序列化。NotSerializableException通知您在上下文(堆栈或堆)中存在一个不可序列化的对象,这会阻止流水线被序列化。因此,请尽量只使用可序列化的对象。如果不可能,您可以使用@NonCPS注释标记使用此类对象的函数,以告诉Jenkins在执行该函数期间不要尝试备份流水线。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月3日 21:53:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63230765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定