Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inexisting diff with jsondiff.Equivalent() mode #29

Closed
yma-het opened this issue Oct 11, 2024 · 2 comments
Closed

Inexisting diff with jsondiff.Equivalent() mode #29

yma-het opened this issue Oct 11, 2024 · 2 comments

Comments

@yma-het
Copy link

yma-het commented Oct 11, 2024

json1 := []byte(`{"a": { "b": [ {"c": [3,2]}, 2, 1 ]}}`)
json2 := []byte(`{"a": { "b": [ {"c": [2,3]}, 1, 2 ]}}`)
patch, err := jsondiff.CompareJSON(json1[:], json2[:], jsondiff.Equivalent())
if err != nil {
fmt.Println(fmt.Errorf("compare: %w", err))
}
b, err := json.MarshalIndent(patch, "", "    ")
if err != nil {
fmt.Println(fmt.Errorf("marshal indent: %w", err))
}
os.Stdout.Write(b)

result is:

[
    {
        "value": 1,
        "op": "replace",
        "path": "/a/b/1"
    },
    {
        "value": 2,
        "op": "replace",
        "path": "/a/b/2"
    }
]

I expect to have no difference

@wI2L
Copy link
Owner

wI2L commented Oct 11, 2024

That's a weird case indeed.

Dug a bit, and I realized that the difference is triggered by the first element actually, the object containing the c key with an array value.

The first array that are compared for deep equality are [ {"c": [3,2]}, 2, 1 ] and [ {"c": [2,3]}, 1, 2 ]. To test for deep equality, each element from the source and target are hashed, and it checks if each element exist in each array, regardless of their position.

However, in this situation, the first item in each array ({"c": [3,2]} and {"c": [2,3]}) hashes to a different digest, because the hashing function ignores the Equivalent option.

The arrays, in this example could be sorted because we know that the underlying types of the elements are the same, but in cases where different types are present in the array, it would be impossible to ensure a "stable" ordering to produce a unique hash digest value.

I'll try to experiment with different solutions to see if it can be solved without adding some overhead.

@wI2L
Copy link
Owner

wI2L commented Nov 11, 2024

@yma-het Found a satisfying fix for this issue. I'll merge it ASAP.

@wI2L wI2L closed this as completed in 19a2a0a Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants