我在Jenkins管道中有以下代码:
stage ("distribution"){
steps{
script{
def rules = [
service_name: "core",
site_name: "*",
city_name: "*",
country_codes: ["*"]
]
amd_distribution_distribute_bundle distribution_rules: rules
}
}
}
如您所见,它是一个map参数。如何使用Groovy代码将其转换为JSON文件?最后,它应该像:
{
"distribution_rules": [
{
"service_name": "core*",
"site_name": "*",
"city_name": "*",
"country_codes": ["*"]
}
]
}
我尝试了以下命令,但没有帮助:
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)
}
答案 0 :(得分:1)
您无需在JsonBuilder
文件中混合JsonOutput
和amd_distribution_distribute_bundle.groovy
。 JsonOutput.toJson(map)
方法采用常规的Map
并将其转换为等效的JSON对象。默认情况下,它创建一个平面单行文件。如果希望获得所谓的漂亮印刷,则需要使用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]])
}
输出:
$ 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]]))
}
输出:
$ cat rootKey
{
"distribution_rules": [
{
"service_name": "core",
"site_name": "*",
"city_name": "*",
"country_codes": [
"*"
]
}
]
}%