Forum Discussion

vivekkulkarni's avatar
vivekkulkarni
Occasional Contributor
3 years ago
Solved

Comparing Json node values against each other

 Hi Team,

 

I have query regarding the json values comparison.

 

I have request say Request-1 and gives response as Response-1. Gives 10 node values

One more request say Request-2 and gives response as Respnse-2. Gives 10 node values

 

I need to compare both response values of all the node values which are common to both.

 

Kindly let me know. I added smart assertion to do comparison, but if node value changes from 10 to 11 the fails to compare or may miss to validate. 

 

Thanks,

Vivek Kulkarni

  • Hi ChrisAdams,

     

    I used part of you logic and got the solution. 

    1. Converted both json responses to string and created objects of it (Using jsonSlurper()) with parsing

     

    //Stored response

    def response1 = context.expand( '${TestCaseName#Response}' )
    def response2 = context.expand( '${TestCaseName#Response}' )

    def jsonSlurper = new JsonSlurper();

     

    //Parsing the response received
    def resp1_obj = jsonSlurper.parseText( response1.toString());
    def resp2_obj = jsonSlurper.parseText( response2.toString());

     

    2. Accessed json file content with Key

    resp1_obj.key_value[i]

    resp2_obj.key_value[i]

     

    3. Parameterized the key indexing ('i' value parameterized)

    4. Compared the node values one after teh other using for loop.

    for(int i=0;i<5;i++)

    {

          if(resp1_obj.key_value[i] == resp2_obj.key_value[i])

               log.info("PASS")

          else

               log.error("FAILED")

               break

    }

    Thanks once again for the solution and response. 

     

    Thanks & Regards,

    Vivek Kulkarni

      

     

8 Replies

  • ChrisAdams's avatar
    ChrisAdams
    Champion Level 3

    Hi,

     

    I'd suggest a Groovy step.  In a Groovy step you can write a script to read responses from both calls and compare.

     

    Look up context.expand to obtain the responses.

     

    Look up JSON Slurper to convert responses to JSON.

     

    Once you have both responses in JSON, you can iterate over one and compare properties with the corresposning property in response 2.

    • vivekkulkarni's avatar
      vivekkulkarni
      Occasional Contributor

      Hi Chris,

       

      Thanks for teh quick response. I tried the groovy, but it compares specific node data. I want to compare teh data of all the nodes present. Iteration is teh challenge. Can you please post related to that. How can I traverse and validate values.

       

      If you require can post json files of the response data.

       

      Thanks,

      Vivek Kulkarni

  • richie's avatar
    richie
    Community Hero
    Hey vivekkulkarni,

    Just to clarify what you want to do.

    You have a test case with Request1. Within the same test case you have Request2.
    You want to compare the content of the results of Response1 against the results of Response2....is that correct?

    If thats correct, there's a couple of ways to do this. I tend to save the response content into a properties step and use groovy to do the compare.

    Pretty sure the other forum users will have different/better options though.

    Cheers,


    Rich
    • vivekkulkarni's avatar
      vivekkulkarni
      Occasional Contributor

      Hi Richie,

       

      Thanks for the answer. I have 2 different APIs calls. The response of two API contains common fields and data. Want to compare those data against each other. Hope scenario is clear.  

      It would be great if the solution provided by you works for this scenario as well.

      If you have any video tutorial or code sample for you solution that helps me to get understand better.

       

       Thanks,

      Vivek Kulkarni

      • ChrisAdams's avatar
        ChrisAdams
        Champion Level 3

        Hi,

         

        This took a bit longer than expected.  Bit of pain marshalling objects, JSON objects, string etc.

         

        To model the scenario, I created three Groovy Script steps in a Test Case.  The first two create an object and converts to JSON.  These mimic your responses.

         

        The names of the first two scripts are important as they used used in the last step.

         

        E.g.  Get Response 1 JSON - Groovy Script

        // We need this to create our JSON object.
        import groovy.json.*;
        
        // Define a play class
        class ResponseOneClass {
        	
        	String propOne = null;
        	String propTwo = null;
        	String propThree = null;
        	String propFour = null;
        	String propFive = null;
        
        	ResponseOneClass(valueOne, valueTwo, valueThree, valueFour, valueFive) {
        		this.propOne = valueOne;
        		this.propTwo = valueTwo;
        		this.propThree = valueThree;
        		this.propFour = valueFour;
        		this.propFive = valueFive;	
        	}
        
        	
        }
        
        // Create an object.
        def responseOneObj = new ResponseOneClass("One", "Two", "Three", "Four", "Five");
        log.info(responseOneObj.propOne);
        
        // Create JSON String.
        def responseOneJson = JsonOutput.toJson(responseOneObj);
        log.info(responseOneJson);
        
        return(responseOneJson.toString());

         

        And now our second response...

         

        E.g. Get Response 2 JSON - Groovy Script

        // We need this to create our JSON object.
        import groovy.json.*;
        
        // Define a play class
        class ResponseTwoClass {
        	
        	String propThree = null;
        	String propFour = null;
        	String propFive = null;
        	String propSix = null;
        	String propSeven = null;
        
        	ResponseTwoClass(valueThree, valueFour, valueFive, valueSix, valueSeven) {
        		this.propThree = valueThree;
        		this.propFour = valueFour;
        		this.propFive = valueFive;	
        		this.propSix = valueSix;	
        		this.propSeven = valueSeven;	
        		
        	}
        
        	
        }
        
        // Create an object.
        def responseTwoObj = new ResponseTwoClass( "Three", "Four", "Five", "Six", "Seven");
        log.info(responseTwoObj.propSeven);
        
        // Create JSON String.
        def responseTwoJson = JsonOutput.toJson(responseTwoObj);
        log.info(responseTwoJson);
        
        return(responseTwoJson.toString());
        

         

        Now, the final script.

        // We need this to create our JSON object.
        import groovy.json.*;
        
        // Get our two responses
        def responseOneJson = context.expand( '${Get Response 1 JSON - Groovy Script#result}' );
        def responseTwoJson = context.expand( '${Get Response 2 JSON - Groovy Script#result}' );
        
        // Bit of logging
        log.info(responseOneJson.toString());
        log.info(responseTwoJson.toString());
        
        // Use JSON Slurper to create objects.
        def jsonSlurper = new JsonSlurper();
        def responseOneObj = jsonSlurper.parseText( responseOneJson.toString() );
        def responseTwoObj = jsonSlurper.parseText( responseTwoJson.toString() );
        
        log.info(responseOneObj.propOne);  // Ooo, we can access it like an object.
        
        // Let's get the keys from our objects as we don't know what props are in our objects!
        def responseOneKeys = responseOneObj.keySet();
        log.info(responseOneKeys);
        def responseTwoKeys = responseTwoObj.keySet();
        log.info(responseTwoKeys);
        
        // For each key in response 1, see if it exists in response 2.  If it does, run an assertion.
        for (key in responseOneKeys) {
        	if (responseTwoKeys.contains(key)){
        		// Common property.  Now we can access our obj property by a variable!!
        		// Try switching the == to != to show failure.
        		assert responseOneObj[key] == responseTwoObj[key];
        	} else {
        		log.info("${key} is not in responseTwo");
        	}
        }