5

I have the below code in Jenkins pipeline:

stage ("distribution"){
            steps{
                script{
                    def rules = [
                            service_name: "core", 
                            site_name: "*", 
                            city_name: "*", 
                            country_codes: ["*"]
                ]
                    amd_distribution_distribute_bundle distribution_rules: rules
                    }
                }
            }

As you can see, it's a map parameter. How can I convert it to the JSON file using Groovy code? At the end it should look like:

{
  "distribution_rules": [
    {
      "service_name": "core*",
      "site_name": "*",
      "city_name": "*",
      "country_codes": ["*"]
    }
  ]
}

I tried the below command but it didn't help:

import groovy.json.JsonBuilder
import groovy.json.JsonOutput

def call(Map parameters)
{
    def DISTRIBUTION_RULES = parameters.distribution_rules
    def json = new groovy.json.JsonBuilder()
    json rootKey: "${DISTRIBUTION_RULES}"
    writeFile file: 'rootKey', text: JsonOutput.toJson(json)
}
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
arielma
  • 1,308
  • 1
  • 11
  • 29

1 Answers1

10

There is no need to mix JsonBuilder and JsonOutput in your amd_distribution_distribute_bundle.groovy file. The JsonOutput.toJson(map) method takes a regular Map and translates it to the JSON object equivalent. By default it creates a flat single line file. If you expect to get so-called pretty print, you need to use combination of JsonOutput.prettyPrint(JsonOutput.toJson(map)).

Flat print

import groovy.json.JsonOutput

def call(Map parameters) {
    def DISTRIBUTION_RULES = parameters.distribution_rules

    writeFile file: 'rootKey', text: JsonOutput.toJson([distribution_rules: [DISTRIBUTION_RULES]])
}

Output:

$ cat rootKey
{"distribution_rules":[{"service_name":"core","site_name":"*","city_name":"*","country_codes":["*"]}]}%    

Pretty print

import groovy.json.JsonOutput

def call(Map parameters) {
    def DISTRIBUTION_RULES = parameters.distribution_rules

    writeFile file: 'rootKey', text: JsonOutput.prettyPrint(JsonOutput.toJson([distribution_rules: [DISTRIBUTION_RULES]]))
}

Output:

$ cat rootKey
{
    "distribution_rules": [
        {
            "service_name": "core",
            "site_name": "*",
            "city_name": "*",
            "country_codes": [
                "*"
            ]
        }
    ]
}%     
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131