有什么办法JSON比较忽略整个段放错了吗? [英] Is there any way the JSON comparison ignores the whole section misplaced?

查看:267
本文介绍了有什么办法JSON比较忽略整个段放错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较两个JSON对象。当'key:value'对顺序改变时,我可以使用 JSON.parse ,在比较期间,测试通过这样:

  doc1 ='{
KayA:Value_A,
KeyB:value_B
}'

doc2 ='{
KeyB:value_B,
KayA:Value_A
}'

doc1 = JSON .parse(doc1)
doc2 = JSON.parse(doc2)

expect(doc1).to eq(doc2)#true
pre>

但是当节,数组或内容块的顺序改变时,如果我执行相同的比较逻辑,我的断言失败,如下所示:

  doc1 ='{
keys:[
{
KayA:Value_A ,
KeyB:value_B
},
{
KayC:Value_C,
KeyD:value_D
}
]
}'

doc2 ='{
keys:[
{
KayC:Value_C,
KeyD:value_D
},
{
KayA:Value_A,
KeyB:value_B
}
]
}'

doc1 = JSON.parse(doc1)
doc2 = JSON.parse(doc2)

expect ).to eq(doc2)#false

有没有我可以比较即使一个块更改?

解决方案

问题是散列和数组有不同的平等想法。请考虑这些:

  {a:1,b:2} == {a:1,b:2} ; true 
{a:1,b:2} == {b:2,a:1}#=> true

[1,2] == [1,2]#=> true
[1,2] == [2,1]#=> false

一旦等式检查命中嵌入式数组,Ruby就会发现数组不匹配,所以。



你看到的结构有多远,你仍然会得到相同的结果,除非你自己确定一个数组是相同的。


I am trying to compare two JSON objects. When a 'key:value' pair order changes, I can use JSON.parse, and during comparison, the test passes like this:

doc1 = '{
    "KayA": "Value_A",
    "KeyB": "value_B"
}'

doc2 = '{
    "KeyB": "value_B",
    "KayA": "Value_A"
}'

doc1 = JSON.parse(doc1)
doc2 = JSON.parse(doc2)

expect(doc1).to eq(doc2) # true

But when the order of a section, an array, or a block of content changes, my assertion fails if I do the same comparison logic like below:

doc1 = '{
    "keys": [
        {
            "KayA": "Value_A",
            "KeyB": "value_B"
        },
        {
            "KayC": "Value_C",
            "KeyD": "value_D"
        }
    ]
}'

doc2 = '{
    "keys": [
        {
            "KayC": "Value_C",
            "KeyD": "value_D"
        },
        {
            "KayA": "Value_A",
            "KeyB": "value_B"
        }
    ]
}'

doc1 = JSON.parse(doc1)
doc2 = JSON.parse(doc2)

expect(doc1).to eq(doc2) # false

Is there anyway I can compare even if a block changes?

解决方案

The problem is that hashes and arrays have different ideas of equality. Consider these:

{a:1, b:2} == {a:1, b:2} # => true
{a:1, b:2} == {b:2, a:1} # => true

[1,2] == [1,2] # => true
[1,2] == [2,1] # => false

Once the equality check hits the embedded arrays, Ruby sees that the arrays don't match and says so.

It doesn't matter how far into the structure you look, you'll still get the same result unless you can determine on your own that one array is the same as the other.

这篇关于有什么办法JSON比较忽略整个段放错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆