akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.08k stars 814 forks source link

Add API to compare JSONs regardless of key/element ordering #514

Closed givascu closed 4 years ago

givascu commented 4 years ago

From the documentation:

  • Two arrays are equal if they have the same number of elements and each element in the first array is equal to the corresponding element in the second array.
  • Two objects are equal if they have exactly the same keys and the value for each key in the first object is equal to the value of the corresponding key in the second object.

The current implementation of json_equal() compares strictly against the order of object keys or array elements.

As a user, I want to be able to compare JSONs regardless of the ordering of object keys or array elements. To not break the API backward-compatibility, a new function can be added. Some naming suggestions: json_equivalent(), json_is_same(), json_equal_deep(), etc.

akheron commented 4 years ago

When comparing objects, the key ordering shouldn't matter. If it currently does, that's a bug.

givascu commented 4 years ago

When comparing objects, the key ordering shouldn't matter. If it currently does, that's a bug.

Right, I hastily misread that bit. My point still stands for array elements though. Thanks.

P.S. Feel free to edit the issue in any way.

Zer0-One commented 4 years ago

IMHO, it should be up to the user to do their own unordered comparison if that's something they need. If jansson does it, then it'll have to decide between:

  1. Sorting the input arrays without modifying them (which is important, because JSON arrays are ordered), which is going to be potentially very expensive with respect to memory.
  2. Doing an exhaustive search of the second array for each element in the first array, which requires no extra memory, but will be slow as hell for large arrays which are equal.

That said, if @akheron is interested in adding a naive json_array_equal_unordered() (or something like that) convenience function (or macro?) that does a simple exhaustive search of the array, I'd be willing to try writing a PR for it.

akheron commented 4 years ago

I don't think using arrays in such a way should be a feature of Jansson. That's just not how arrays are meant to be used.