jenkinsgroovyjenkins-groovygroovyshellgroovy-console

How to update JSON payload when values are embedded in backslash in Groovy


In Groovy I have to update values in JSON payload and make an API call. I am running into challenges while updating payload as the fields are embedded in backslash. Is there a simpler way to directly update the servers in below payload i.e update 1. JSON payload to 2. Updated JSON payload (updating name and host values).

1. JSON payload:

    {
    "environment": "dev",
    "config": "Create",
    "configType": "Server",
    "ServerName": "",
    "Servers": "[\\{\"name\":\"Server-test_1\",\"host\":\"test.com\",\"port\":\"443\",\"tls\":\"2-way\"}]",
    "tsHost": "",
    "tsPort": "",
    "tsSSLOption": "1-way"
    }

2. Updated JSON payload:

    {
    "environment": "dev",
    "config": "Update",
    "configType": "Server",
    "ServerName": "",
    "Servers": "[\\{\"name\":\"Server-test_2\",\"host\":\"test123.com\",\"port\":\"443\",\"tls\":\"2-way\"}]",
    "tsHost": "",
    "tsPort": "",
    "tsSSLOption": "1-way"
    }

Tried below (losing backslash in conversion process):

Code:

    def json = $/ {
    "environment": "dev",
    "config": "Create",
    "configType": "Server",
    "ServerName": "",
    "Servers": "[\\{\"name\":\"Server-test_1\",\"host\":\"test.com\",\"port\":\"443\",\"tls\":\"2-way\"}]",
    "tsHost": "",
    "tsPort": "",
    "tsSSLOption": "1-way"
    } 
/$
    def parser = new JsonSlurper()
    def jsonResp = parser.parseText(json)
    println(jsonResp.Servers)
    jsonResp.Servers.name = "Server-test_2"
    jsonResp.Servers.host = "test123.com"

Solution

  • Servers is a string in your initial json - you have to parse it

    import groovy.json.*
    
    def json = $/ {
        "environment": "dev",
        "config": "Create",
        "configType": "Server",
        "ServerName": "",
        "Servers": "[{\"name\":\"Server-test_1\",\"host\":\"test.com\",\"port\":\"443\",\"tls\":\"2-way\"}]",
        "tsHost": "",
        "tsPort": "",
        "tsSSLOption": "1-way"
        } 
    /$
    def parser = new JsonSlurper()
    def jsonResp = parser.parseText(json)
    println(jsonResp.Servers)
    
    def servers = parser.parseText(jsonResp.Servers)
    servers[0].name="Server-test_2"
    servers[0].host="test123.com"
    jsonResp.Servers = JsonOutput.toJson(servers)
    json = JsonOutput.prettyPrint(JsonOutput.toJson(jsonResp))