1

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?

USer22999299
  • 5,284
  • 9
  • 46
  • 78
  • func you are looking for is JsonOutput.toJson(...) – daggett Aug 11 '22 at 06:49
  • @daggett JsonOutput.toJson is not escaping the value into an escaped string, any idea on how to convert the json value object into string representation? – USer22999299 Aug 11 '22 at 07:00
  • it is converting the object into json string. then if you convert the wrapper object into json - you get an expected result – daggett Aug 11 '22 at 09:31

1 Answers1

2
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}}"}
daggett
  • 26,404
  • 3
  • 40
  • 56