Is there any way the JSON comparison ignores the w

2019-09-17 13:49发布

问题:

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.