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)
}
JsonSlurper. JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .
The Jenkinsfile is written using the Groovy Domain-Specific Language and can be generated using a text editor or the Jenkins instance configuration tab. The Declarative Pipelines is a relatively new feature that supports the concept of code pipeline.
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))
.
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":["*"]}]}%
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": [
"*"
]
}
]
}%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With