Forum Discussion

ssteinhorst's avatar
Occasional Contributor
7 years ago

validate json items in an array

I have an API that returns JSON and I'm unsure the best way to get to the element I'm trying to check. Here is a sample:



	"Records": [{
		"correlation_id": null,
		"date": "2017-12-26",
		"pay_period_end_date": "2017-12-31",
		"work_unit": {
			"id": "a1B1H00121212WUdfsdfX"
	}, {
		"correlation_id": null,
		"date": "2017-12-26",
		"pay_period_end_date": "2017-12-31",
		"work_unit": {
			"id": "kdkd9df980sdkdn2"

I'm trying to check that a specific Records[<somevalue>] value is present. We aren't always guaranteed to have them in the same order so I need to check if any object in the array has a of kdkd9df980sdkdn2.


I can get a jsonpath that will give me an array of the values but can't seem to see a way to validate that since the results changing order still causes the validation to fail. 


Is there a feature of soapui that I'm missing that could do this? Any suggestions on how to tackle this problem? Thanks!


2 Replies

  • JoostDG's avatar
    Frequent Contributor

    Hi ssteinhorst,


    There is no build in easy way to validate on a certain value as long as it is NOT always present in the same node.

    There are options however to dynamically assert this.

    Easy option can be just to check whether the value exists in the response.

    Either via the contains assertion:


    Or via the JSONPath expression if you want to check specifically in a certain array, for instance:


    Otherwise, if you want to check really that it exists only in the work_unit id element you will have to use groovy.

    I think it should work something like this. 


    def Records = context.expand('${yourtestcase#Response#$[\'Records\']}')
    //Records is now a string of all your items in the array
    def RecordsArray = JsonUtil.parseTrimmedText(Records );
    //now it is convereted back to an arry
    def n = eigenschappenArray.size()
    //we count how many records items  there are in the array
    for (i=0; i < n; i+= 1)
    //we create a for loop to go through all the elements of the array
    def work_unit_id = context.expand ('${yourtestcase#Response#$[\'Records\']['+i+']['\work_unit\'][\'0\'][\'id\']}')
    if (work_unit_id  == "kdkd9df980sdkdn2")
    { ("work_unit id is found in node "+i)}



    • ssteinhorst's avatar
      Occasional Contributor

       As a follow up, in the script posted how does that assert in a soap ui test? Would you run that script as a test step then assert on the 'work_unit id is found in node' text? 


      And thanks! That is really helpful!


      I did end up using a script assert which seems to have solved my problems. The assert looks like this: 


      def json = new groovy.json.JsonSlurper().parseText(context.response)