我想从Jenkins Pipeline脚本中按以下方式构建为json
{
type:"create_instance",
order:{
"system_order_specs":{
"location":{ "name": "${params.LOCATION_NAME}" },
"zones":[
{
"$ESXI_TYPE":params.ESXI_COUNT,
"vlan":[
{
"type": "${params.VLAN_TYPE}",
},
{
"type": "${params.VLAN_TYPE}",
}
]
}
],
"create_dp_instance": false
}
}
}
我已经尝试按照此网址Create JSON strings from Groovy variables in Jenkins Pipeline
中的建议使用以下方法def data = [
type:"create_instance",
order:[
"system_order_specs":[
"environment_type":"PROD",
"location":[ "name": "${params.LOCATION_NAME}" ],
"zones":[
[
"$ESXI_TYPE":params.ESXI_COUNT,
"vlan":[ [
"type": "${params.VLAN_TYPE}",
] ]
]
],
"create_dp_instance": false
]
]
]
writeJSON(file: 'initial_temp.json', json: data)
但这会引发异常,该异常提示我认为数据格式不正确。
也尝试使用shell进行简单的echo,但是会创建一个没有任何双引号'“'的JSON。
下面的示例代码:
sh `echo { \"type\":\"create_instance\", \"job_id\":$JOB_ID, \"order\":{ \"system_order_specs\": "123" } } > xyz.json`
以下方法似乎可行,但我确信这不是最佳答案。因此,我正在为此寻找最佳解决方案。
node{
def data = readJSON text: '{}'
def order = readJSON text: '{}'
def sys_order = readJSON text: '{}'
def location = readJSON text: '{}'
def vlan = readJSON text: '{}'
def zones = readJSON text: '{}'
data.type = "create_instance"
location.name = "${params.LOCATION_NAME}" as String
sys_order.environment_type = 'PROD'
sys_order.system_number = "${params.SYSTEM_NUMBER}" as String
sys_order.company = company
sys_order.location = location
zones["${params.ESXI_TYPE}"] = params.ESXI_COUNT
script {
if (params.VLAN_TYPE != 'nil') {
vlan.type = "${params.VLAN_TYPE}" as String
zones.vlan = [vlan]
}
}
sys_order.zones = [zones]
order.system_order_specs = sys_order
data.order = order
writeJSON(file: 'initial_temp.json', json: data)
}