解析 Json 数据并插入 Yaml

Parse Json data and inserting into Yaml

我想使用 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

我认为你的问题是这一行:

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

问题出在 "$parsedJsonData" 部分。

这将调用插值数据的toString()方法,它看起来是Map

要将其转换为 JSON 字符串表示形式,您可以在管道中使用 groovy.json.JsonOutput.html#toJson(java.util.Map) 方法。

如果它确实是 Map(或其他一些类型),它将被 脚本安全插件 默认列入白名单(参见 here). If not, it may be blacklisted (see here ).

import groovy.json.JsonOutput

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