简体   繁体   中英

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... ie 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 .

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM