如何将Groovy Map转换为JSON

时间:2019-11-12 22:07:44

标签: groovy jenkins-pipeline jenkins-groovy

我在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)
}

1 个答案:

答案 0 :(得分:1)

您无需在JsonBuilder文件中混合JsonOutputamd_distribution_distribute_bundle.groovyJsonOutput.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": [
                "*"
            ]
        }
    ]
}%