Forum Discussion

siva90144's avatar
siva90144
New Contributor
6 years ago

How to format json response body in soap UI

am getting json body from rest response with escaped cahrs as shown below. How to format josn response in soapUI using groovy script?

 

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

       

Expected Output:            

      {

                     "employee":

                           {

                              "name": "John",

                              "age": 30,

                              "city": "New York"

                          }

                }

2 Replies

  • Use JsonSlurper and JsonOutput:

    import groovy.json.JsonSlurper
    import groovy.json.JsonOutput
    
    String response = $/        {
              "employee": "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
         }/$
         
    def parsedResponse = new JsonSlurper().parseText(response)

    String formattedResponse = parsedResponse
    .with (JsonOutput.&toJson >> JsonOutput.&prettyPrint)

    However, if that's really the response you're getting, it looks like the API has a problem, because it's sending the employee as a string instead of an object.

    assert parsedResponse.'employee' instanceof String
    assert parsedResponse.'employee' == '{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}

     If that is really how the API works, you could do this:

    import groovy.json.JsonSlurper
    import groovy.json.JsonOutput
    
    String response = $/        {
              "employee": "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
         }/$
         
    def parsedResponse = new JsonSlurper().parseText(response)
    parsedResponse.'employee' = new JsonSlurper().parseText(parsedResponse.'employee')
    
    String formattedResponse = parsedResponse 
        .with (JsonOutput.&toJson >> JsonOutput.&prettyPrint)