user5505796
user5505796

Reputation:

compare json files irrespective of field position in groovy using soap ui

Consider that I have a JSON file (named expectedResponse.json) that has some fields and values. Now I have to write a groovy script that compares the two files which will not bother even if the position of the field is jumbled... i.e if my expectedResponse has "name":"abc" as the 1st field then it should not fail if my generatedResponse has "name":abc as the 2nd field.

Upvotes: 0

Views: 2121

Answers (1)

albciff
albciff

Reputation: 18507

Try with JsonSlurper:

import groovy.json.JsonSlurper

def json1 = '{"name" : "abc", "value": "123", "field" : "xyz"}'
def json2 = '{"field" : "xyz", "value": "123" ,"name" : "abc"}'

def slurp1 = new JsonSlurper().parseText(json1)
def slurp2 = new JsonSlurper().parseText(json2)

assert slurp1 == slurp2

It converts json to an object which is instanceof Map, and map are equals if have same size, and keys and values despite their order.

Note that as other comments this solutions doesn't work for json arrays like

def json1 = '[{"n":"3","sv":"0.3"},{"n":"2","sv":"0.2"},{"n":"1","sv":"0.1"},{"n":"5","sv":"0.5"},{"n":"4","sv":"0.4"}]'    
def json2 = '[{"n":"1","sv":"0.1"},{"n":"2","sv":"0.2"},{"n":"3","sv":"0.3"},{"n":"4","sv":"0.4"},{"n":"5","sv":"0.5"}]'

Since the slurper for this case not convert the object to instanceof Map

Hope it helps,

Upvotes: 1

Related Questions