解析Json数据并插入Yaml

问题描述 投票:2回答:1

使用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
json jenkins yaml jenkins-pipeline jenkins-declarative-pipeline
1个回答
1
投票

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

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

问题是"$parsedJsonData"部分。

这将调用内插数据的toString()方法,该方法似乎是Map

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

如果它确实是Map(或其他一些类型),它将默认由脚本安全插件列入白名单(请参阅here)。如果没有,它可能会被列入黑名单(参见here)。

import groovy.json.JsonOutput

// ...
yamlData['components']['component1']['data']['chef']['default'] = JsonOutput.toJson(parsedJsonData)
© www.soinside.com 2019 - 2024. All rights reserved.