cancel
Showing results for 
Search instead for 
Did you mean: 

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

Highlighted
Frequent Contributor

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

As captioned:

 

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]
1 REPLY 1
Highlighted
Moderator

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

Great solution, @aaronpliu!

 

For convenience, let me quote the initial task for the community members:

 

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

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 the name=John&age=30&city=New%20York string."

 

You have a good chance to win in the API Summer event this week, just keep creating new topics. You can also get extra points to your score if you reply to the featured topics listed here.

 

Thank you for sharing!


Olga Terentieva
SmartBear Assistant Community Manager

New Here?
Join us and watch the welcome video:
Announcements
Top Kudoed Authors