Convert a flat JSON object to x-www-form-urlencoded

Originally published by aaronpliu on September 28, 2021 in the previous SmartBear Community.

Question

How to create a Groovy script, which transforms a non-nested JSON object to the x-www-form-urlencoded format before sending it in the request body.

Example: converting this object:

{
  "name": "John",
  "age": 30,
  "city": "New York"
}

should result in this string:

name=John&age=30&city=New%20York 

Answer

def jsonData = '''
{
	"name":"John",
	"age":30,
	"city":"New York"	
}
'''
def slurper = new groovy.json.JsonSlurper().parseText(jsonData)
def str = new StringBuilder()
def iter = slurper.keySet().iterator()
while(iter.hasNext()){
	def key = iter.next().toString()
	def value = slurper.get(key).toString().trim().replaceAll(" ","20%")
	str.append("$key=$value&")
}
log.info str[0..str.size()-2]