Forum Discussion

radhika1's avatar
radhika1
Contributor
7 years ago

Need to know how to compare two json response one with json object and other with json array .

  • Alex99's avatar
    Alex99
    7 years ago

    How about this:

     

    log.info("start")
    
    def listA = []
    def listB = []
    def slurperA = new JsonSlurper().parseText(<json 1 text>)
    def slurperB = new JsonSlurper().parseText(<json 2 text>)
    
    slurperA.each { key, value ->
    	loop(listA, key, value)
    }
    
    slurperB.each { key, value ->
    	loop(listB, key, value)
    }
    
    log.info("matches: " + listA.intersect(listB))
    log.info("mismatches A: " + listA.minus(listB))
    log.info("mismatches B: " + listB.minus(listA))
    log.info("done")
    
    
    def loop(list, key, value) {
    	if(value.class == null) {
    		if(value != null && !value.isEmpty()) {
    			value.each { k, v ->
    				loop(list, (key + '.' + k), v)
    			}
    		} else {
    			//log.warn(key + ": empty")
    			list.add((key))
    		}
    	} else if(value.class == ArrayList) {
    		value.each {
    			loop(list, key, it)
    		}
    	} else {
    		//log.info(key + " = " + value)
    		list.add(key + " = " + value)
    	}
    }
    

    Will give you something like this:

    Thu Nov 01 20:43:49 CET 2018:INFO:matches: [consumerProfile.consumerProfileIdentifier.profileID = 85750290, consumerProfile.consumerProfileIdentifier.type = UCPID,...
    Thu Nov 01 20:43:49 CET 2018:INFO:mismatches A: [_class = com.moneygram.coreservices.ProfileCacheService.web.model.ConsumerProfileCacheDocument, consumerProfile.auditEvent.agentID = 40307666,...
    Thu Nov 01 20:43:49 CET 2018:INFO:mismatches B: [consumerProfile.auditEvent.agentID, consumerProfile.auditEvent.sourceSystemUserID, consumerProfile.auditEvent.updateDate = 2018-10-30T11:34:35-05:00,...
    • JHunt's avatar
      JHunt
      Community Hero

      Hi Radhika,

       

      How would you normally do it if they both had single objects? However you normally would, you should be able to do the same thing but just get the first object out of the the list.

       

      For example:

       

      assert json1.'consumerProfile'.'consumerProfileIdentifier'.'profileID' == json2.'consumerProfile'.'consumerProfileIdentifier'[0].'profileID'

      • radhika1's avatar
        radhika1
        Contributor
        Can you help me how to do this for all objects if possible.