简体   繁体   中英

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 ie 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"

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM