Forum Discussion

brsteele75's avatar
brsteele75
New Contributor
11 years ago

Assert a JSON array response is not empty

I'm new to the Ready! API (REST) tool and have no programming background.  I'm having trouble asserting that an array that is returned is not empty. 

 

I'm using a GET call to return a list. This list is static and based on fixture data. Currently I am using the "JSONPath Count" to assert  a JSON node $[12] is present 1 time, but that feels dirty.

 

I'm wondering if there is a better way to simply assert that the array is not empty?

1 Reply

  • nmrao's avatar
    nmrao
    Icon for Champion Level 1 rankChampion Level 1

    Here is an example code

    import net.sf.json.groovy.JsonSlurper
    def jsonArray = '''{
        "employees":[
    		{"firstName":"John", "lastName":"Doe"},
    		{"firstName":"Anna", "lastName":"Smith"},
    		{"firstName":"Peter","lastName":"Jones"}
    	]
    }'''
    
    def jsonSlurper = new JsonSlurper()
    def object = jsonSlurper.parseText(jsonArray)
    def employees = object.employees
    log.info employees instanceof List
    log.info employees.size()
    if (employees){
    	log.info "Employe array is not empty"
    } else {
    	log.info "Employee array is empty"
    }

     An example with empty array

     

    import net.sf.json.groovy.JsonSlurper
    def jsonArray = '''{
        "employees":[]
    }'''
    def jsonSlurper = new JsonSlurper()
    def object = jsonSlurper.parseText(jsonArray)
    def employees = object.employees
    if (!employees) {
    	log.warn "Array is empty" 
    }

     Hope this helps