Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Json data and inserting into Yaml

Using a jenkins pipeline I want to parse a json file and append some value to one of my Yaml file. Below is my Json file.

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

And, here is how my Yaml file looks:

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

Here is the pipeline script that I am using:

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

The output I am getting is like this:

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

But I am excepting the output like this:

id: example
components:
  component1:
    type: example1
    data:
      action:
        first: FullClone
      chef:
        default: '{"example": { "example": "test" }, "run_list": ["recipe[example::example"]}'
  component2:
    type: example2
like image 754
linuxnewbee Avatar asked Aug 18 '26 08:08

linuxnewbee


1 Answers

I think your problem is this line:

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

The problem being the "$parsedJsonData" part.

This will call the toString() method of the interpolated data, which appears to be a Map.

To convert it to the JSON string representation, you could make use of the groovy.json.JsonOutput.html#toJson(java.util.Map) method in your pipeline instead.

If it is indeed a Map (or a few other types) it will be whitelisted by default by the Script Security Plugin (see here). If not, it may be blacklisted (see here).

import groovy.json.JsonOutput

// ...
yamlData['components']['component1']['data']['chef']['default'] = JsonOutput.toJson(parsedJsonData)
like image 117
mkobit Avatar answered Aug 19 '26 23:08

mkobit