使用soap ui比较json文件,而不考虑groovy中的字段位置 [英] compare json files irrespective of field position in groovy using soap ui
问题描述
即,如果我的expectedResponse具有name:abc作为第一个字段,那么如果我的generatedResponse具有name:abc作为第二个字段,那么它不应该失败。
使用 JsonSlurper
:
import groovy.json.JsonSlurper
def json1 ='{name:abc,value:123,field:xyz}'
def json2 ='{field:xyz, value:123,name:abc}'
$ b $ def slurp1 = new JsonSlurper()。parseText(json1)
def slurp2 = new JsonSlurper()。parseText (json2)
assert slurp1 == slurp2
它将json转换为是 instanceof Map
的对象,如果具有相同的大小,则map是等于的,键和值,尽管他们的顺序。
请注意,作为其他评论这个解决方案不适用于像JSON数组
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}]'
由于这种情况下slurper不会将对象转换为 instanceof Map
希望它有帮助,
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.
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,
这篇关于使用soap ui比较json文件,而不考虑groovy中的字段位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!