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

北慕城南 提交于 2019-12-23 05:14:02

问题


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.


回答1:


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,



来源:https://stackoverflow.com/questions/33429067/compare-json-files-irrespective-of-field-position-in-groovy-using-soap-ui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!