解析Json数据并插入到Yaml中。

3

我想使用Jenkins管道解析JSON文件,并将一些值附加到我的Yaml文件中。以下是我的Json文件。

{
  "id": "test",
  "chef": {
    "attributes": {
      "example": {
        "example": "test"
      }
    },
    "run_list": [
      "recipe[example::example]"
    ] 
  }
}

这是我的Yaml文件的样子:

id: example
components:
  component1:
    type: example1
    data:
      action:
        first: FullClone
      chef:
        default: '{"example1": { "value1": "test123" }, "run_list": ["recipe[example1::example123"]}'
  component2:
    type: example2

这是我正在使用的流水线脚本:

pipeline {
  agent any
  stages {
    stage {
      stpes {
        jsonData = readJSON file: 'test.json'
        yamlData = readYaml file: 'test.yaml'
        parsedJsonData = jsonData.chef
        yamlData['components']['component1']['data']['chef']['default'] = "$parsedJsonData"
        writeYaml file: 'newYaml.yaml', data: yamlData
        sh "cat newYaml.yaml"
      }
    }
  }
}

我得到的输出如下所示:
id: example
status: DR
components:
  component1:
    type: example1
    data:
      action:
        first: FullClone
      chef:
        default: '[attributes:[example:[example:test]], run_list:[recipe[example::example]]]'
  component2:
    type: example2

但是我希望输出结果像这样:
id: example
components:
  component1:
    type: example1
    data:
      action:
        first: FullClone
      chef:
        default: '{"example": { "example": "test" }, "run_list": ["recipe[example::example"]}'
  component2:
    type: example2

你的结果中不需要“attributes:...”,但是缺少一个“{”才能得到良好的结果。请修复一下,好吗?我不太明白你具体期望什么。 - Franck Cussac
我认为他期望的是在默认字段中,数据不相同。 - Hatim
1个回答

2

我认为你的问题在于这一行代码:

yamlData['components']['component1']['data']['chef']['default'] = "$parsedJsonData"

问题出在 "$parsedJsonData" 部分。
这将调用插值数据的 toString() 方法,它似乎是一个 Map
为了将其转换为JSON字符串表示形式,您可以在管道中使用 groovy.json.JsonOutput.html#toJson(java.util.Map) 方法。
如果确实是一个 Map(或其他一些类型),则默认情况下会被 脚本安全插件 的白名单所允许(请参见 这里)。如果不是,则可能被列入黑名单(请参见 这里)。
import groovy.json.JsonOutput

// ...
yamlData['components']['component1']['data']['chef']['default'] = JsonOutput.toJson(parsedJsonData)

你能帮我获取变量parsedJsonDataattributerunlist的值吗? - linuxnewbee
@linuxnewbee 我认为你可以使用与 parsedJsonData['chef']['runlist']parsedJsonData['chef']['attributes'] 相同的访问模式。 - mkobit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接