简体   繁体   中英

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?

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

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