Forum Discussion

groovyguy's avatar
groovyguy
Community Hero
6 years ago
Solved

Script Challenge - 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. 

  • groovyguy's avatar
    groovyguy
    6 years ago

    TanyaYatskovska, there's definitely a world of possibilities that I am just now beginning to understand by hooking into events with groovy scripts. I am going to have to do some more exploring myself though to get a feel for further functionality!

5 Replies

  • TanyaYatskovska's avatar
    TanyaYatskovska
    SmartBear Alumni (Retired)

    Great example Matthew! Thanks for your contribution in API Summer.

    I'm sure your script will help many community members. Do you think it's possible to extend its functionality somehow more?

    • groovyguy's avatar
      groovyguy
      Community Hero

      TanyaYatskovska, there's definitely a world of possibilities that I am just now beginning to understand by hooking into events with groovy scripts. I am going to have to do some more exploring myself though to get a feel for further functionality!