Knowledge Base Article

Unescape Json Strings

I wasn't 100% familiar with JSON strings, or working with events and attaching a groovy script, but after a bit of research I was able to put something together that should work. The challenge was as follows:

 

Unescape JSON Strings
Create a Groovy script, which unescapes JSON strings in the body of a REST API response before the response in shown in the response editor:

Example of original response body:

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

Example of the corresponding modified response body: 

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

Here, for the request that has a response that needs to be escaped, we have to add an Event to the project. That event should be of type "RequestFilter.afterRequest" and should contain the following groovy script:

 

def responseContent = context.httpResponse.responseContent; 
context.httpResponse.responseContent = responseContent.replaceAll("\\\\", "");

I believe this should solve the problem presented in the script challenge. I learned something new, too! I'd be eager to see how other people solve it, or if I am even on the right track. It appears to work for me, though. 

Published 4 years ago
Version 1.0
No CommentsBe the first to comment