Forum Discussion

sonya_m's avatar
sonya_m
SmartBear Alumni (Retired)
4 years ago
Solved

[TechCorner Challenge #15] Fetch a value/data from a JSON response using a Groovy Script

Hello ReadyAPI Community!   We have another task for you to put your ReadyAPI knowledge to the test. Check out the participation rules and the TechCorner Leaderboard here.   In this task, we ...
  • ChrisA's avatar
    4 years ago

    Task: Find a specific value in a JSON response using a Groovy script

     

    This is a solution created for [TechCorner Challenge #15]

     

    Hi,

    Here is my attempt....

     

     

    def TestCaselist=context.testCase.testSuite.getTestCaseList();
    import groovy.json.*;
    
    def jsonSlurper = new JsonSlurper();
    def responseMessage;
    
    def importantString = "some value";  // This is the value to look for....
    
    def testStepName;
    def found = false;
    def returnString = '';
    
    TestCaselist.each{
    
      def steps=it.getTestStepList(); //'it' is used for referring to current item
      steps.each{
        if(it.toString().contains('RestTest')){
          if(it.testRequest.response != null){ 
            // We only want to check steps where there is a response
    
            testStepName = it.name;  // We use this later.
            responseMessage = it.testRequest.response.contentAsString;  // Get the response as string
              if(responseMessage != null){
                // Only continue if message is not null.
                try {
                  // Only proceeding if response parses into JSON
                  def object = jsonSlurper.parseText(responseMessage);
    
                  // Convert JSON back to a string and use contains function to check for importantString
                  if(object.toString().contains(importantString)){
                    // Found one.  Log it, append to return string and set found to true.
                    log.info("Found '" + importantString + "' in Test Step " + testStepName);
                    returnString = returnString + "Found '" + importantString + "' in Test Step " + testStepName + ".\n";
                    found = true;
                  }
                } catch(Exception e){
                  // Not JSON - Don't have to log this, but only trying to ensure we only check JSON response.
                  log.info(e);
                }
              }
            }
          }
        }
    }
    
    if (found) {
      return returnString;
    } else {
      return ("Could not find '" + importantString + "' in any JSON reponse.");
    }

     

  • HimanshuTayal's avatar
    HimanshuTayal
    4 years ago

    Task: Find a specific value in a JSON response using a Groovy script

     

    This is a solution created for [TechCorner Challenge #15]

     

    Hi sonya_m :

     

    Thank you for letting me know, please refer below code,hope this will work

     

     

    import groovy.json.*;
    
    def testCases = testRunner.testCase.testSuite.getTestCaseList()
    def jsonSlurper = new JsonSlurper()
    
    def strToCheck = "VeryImportantString"
    def returnText = ""
    
    testCases.each{
    	def steps = it.getTestStepList();
    	steps.each{
    //		Checking only the rest teststep
    		if(it.config.type.toLowerCase() == "restrequest" ){
    			response = it.getPropertyValue("response")
    //			Checking whose response is not null
    			if(response != null){
    //				getting name to append
    				def testStepName = it.name;
    				def res = jsonSlurper.parseText(response);
    				
    //				checking that desired text exist or not
    				if(res.toString().contains(strToCheck))
    					returnText = returnText + " Found \"" + strToCheck + "\" in Test Step " + testStepName +" \n"
    			}
    		}
    	}
    }
    if (returnText != null || returnText != "")
    	return returnText
    else
    	return ("The value wasn't found")