BruceyBandit BruceyBandit - 3 years ago 68
reST (reStructuredText) Question

Incorrect properties displayed from Json

I am having an issue when trying to collect data from a json using SOAP UI and groovy scripting. Below is an example json:

{
"regions": [{
"regionId": 10,
"hotels": [{
"roomInformation": [{
"hotelRoomId": 1,
"availableRooms": 1,
"roomPrice": 100,
"occupancySequenceOrder": 1,
"providerRoomId": 1,
"isExtranet": true
}],
"regionId": 1,
"hotelId": 1,
"boardTypeId": 1,
"startDate": "2017-10-23T00:00:00",
"endDate": "2017-10-30T00:00:00",
"totalPrice": 1000,
"providerInformation": {
"hotelSpecialOfferDetails": [],
"ratePlanCode": "xxx",
"allAvailableResults": []
},
"providerHotelId": 25
},

{
"roomInformation": [{
"hotelRoomId": 1,
"availableRooms": 1,
"roomPrice": 100,
"occupancySequenceOrder": 1,
"providerRoomId": 1,
"isExtranet": true
}],
"regionId": 1,
"hotelId": 1,
"boardTypeId": 1,
"startDate": "2017-10-23T00:00:00",
"endDate": "2017-10-30T00:00:00",
"totalPrice": 1000,
"providerInformation": {
"hotelSpecialOfferDetails": [],
"ratePlanCode": "ggg",
"allAvailableResults": []
},
"providerHotelId": 31
}
],
"errors": null
}],
"errors": null
}


What I want to do is select the first instance of
providerHotelId
and
ratePlanCode
. To do this I have the groovy script below to tackle this:

def alert = com.eviware.soapui.support.UISupport
import groovy.json.JsonSlurper
def response = testRunner.testCase.getTestStepByName("Search Region").getProperty("Response").getValue();

def jsonRes = new JsonSlurper().parseText(response);

def providerhotelid = jsonRes.regions.hotels.providerHotelId[0].toString()
def rateplancode = jsonRes.regions.hotels.providerInformation[0].ratePlanCode.toString()

log.info providerhotelid

testRunner.testCase.setPropertyValue('providerhotelid', providerhotelid)
testRunner.testCase.setPropertyValue('rateplancode', rateplancode)


This outputs below in my custom properties:


  • providerhotelid - [25,31]

  • rateplancode - [xxx]



The above is incorrect because:


  1. providerhotelid - it displays all provider hotel ids when I only want the first one which should be
    25
    .

  2. rateplancode - is correct but it displays a [] around it and I want this removed. Same goes for providerhotelid.



So for this example my custom properties should display:


  • providerhotelid - 25

  • rateplancode - xxx



How can this be achieved within my groovy script?

Rao Rao
Answer Source

Here is what you need:

//Get all the values, falatten them and get the first one
def providerhotelid = jsonRes.regions.hotels.providerHotelId.flatten()[0]
def rateplancode = jsonRes.regions.hotels.providerInformation.ratePlanCode.flatten()[0]

log.info providerhotelid 
log.info rateplancode

You can quickly try it online Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download