jsongroovyjsonslurper

How to convert JSON value to escaped String in groovy [JsonSlurper]?


i have a groovy script that runs on Jenkins, i have build there a json object using JsonSlurper

The json object is a nested one, i would need to convert the nested json child into escaped string value instead of a json object (that's the requirement :) ).

{"key1":
    {"key2":
       {"key3":true}
    }
 }

Into string escaped value:

{"key1": "  {\"key2\":{\"key3\":true}}  " }

I'm building the json object by using:

def jsont = new JsonSlurper().parseText(row)

doing some manipulation to the json, then need to convert to string:

jsont.key1 = func(jsont.key1) ----> here i want to convert key1 value to escaped string

Any suggestion?


Solution

  • import groovy.json.*
    
    def json = '''{"key1":
        {"key2":
           {"key3":true}
        }
     }
    '''
    
    def obj = new JsonSlurper().parseText(json)
    obj.key1 = JsonOutput.toJson(obj.key1)
    
    json = JsonOutput.toJson(obj)
    

    result:

    {"key1":"{\"key2\":{\"key3\":true}}"}