Is there any way the JSON comparison ignores the whole section misplaced?

那年仲夏 提交于 2019-12-12 00:25:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32747080/is-there-any-way-the-json-comparison-ignores-the-whole-section-misplaced

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