Forum Discussion

anichat26's avatar
anichat26
New Contributor
8 years ago

Handling collection of items in Ready API!

I have a REST API with request json string as follows:-

 

{

     "items":[

     { "itemcode":1, "quantity":5},

     { "itemcode":2, "quantity":6}

     ]

}

 

How can I perform data driven testing on the above request in Ready API?

Thanks in advance for the help.

    • anichat26's avatar
      anichat26
      New Contributor

      Hi TanyaGorbunova,

       

       

       

      {

           "supplierId":"2",

           "supplierName":"Test Supplier",

           "items":[

           { "itemcode":1, "quantity":5},

           { "itemcode":2, "quantity":6},

           .............. //this array of items can have multiple "itemcode" and "quantity" and the count of "items" depends on the number of items I provide for a supplier.

           ]

      }

       

      If it would have been a single item instead of an array, I could have mapped the datasource with individual property of JSON but when the count of data is unknown how can I map it?

      If there is any link for an exact solution, please provide.

       

      • gilugopi's avatar
        gilugopi
        Contributor

        DataSource is not the answer for your need. You need to write sort of goovy script to add more items to your Json. Given below is an example.

         

        Refer to online documentation of groovy libraries JsonSlurper, JsonBuilder or  JsonOutput so that you can write script specific for your need. Given below is an example script for demonstration.

         

        def jsonString = """
        	{
        	     "items":[
        	     { "itemcode":1, "quantity":5},
        	     { "itemcode":2, "quantity":6}
        	     ]
        	}
        """
        def json = new groovy.json.JsonSlurper().parseText(jsonString)
        
        class item{
        	def itemcode;
        	def quantity;
        	
        	item(def itemcode, def quantity){
        		this.itemcode = itemcode
        		this.quantity = quantity
        	}
        }
        
        def item3 = new item(3,7)
        def item4 = new item(4,8)
        
        def jsonBuilder = new groovy.json.JsonBuilder(json);
        List items = jsonBuilder.content.items
        items.add(item3)
        items.add(item4)
        jsonBuilder.content.items = items;
        println jsonBuilder.toPrettyString()

         

        Output

         

        {
        "items": [
        {
        "itemcode": 1,
        "quantity": 5
        },
        {
        "itemcode": 2,
        "quantity": 6
        },
        {
        "itemcode": 3,
        "quantity": 7
        },
        {
        "itemcode": 4,
        "quantity": 8
        }
        ]
        }

         

         Cheers !

        Gilu Gopi