I'm trying to replicate the object-hash npm package in Go and need to be able to support unordered arrays (i.e. ordering of arrays shouldn't matter while deciding whether one JSON is different from another).
Example: The two JSON strings { foo: 1.23e1, bar: { baz: [0, 1, { a: 1 }, { b: 2 }], abc: 12 } } and { foo: 1.23e1, bar: { baz: [1, 0, { b: 2 }, { a: 1 }], abc: 12 } } should give the same output (byte array).
Currently, I'm achieving this through a lot of recursive code, trying to cover all edge cases. Is there a better way of doing this?
Edits:
- To clarify the problem statement further, I'm trying to generate SHA-1 hashes of JSON strings. These JSONs are arbitrarily structured (so can't unmarshal them into a well-defined
struct). While generating these hashes, my client wants me to ignore the ordering of arrays - since any array with the same elements in any order represents the same thing in their system (they're using JSON arrays as unordered lists). - Since I can't assume anything about the structure of these input JSONs, I'm sorting the arrays before hashing them (in my current implementation). For sorting, I'm comparing json-marshalled string representations of the array elements. Before sorting, I'm also checking if any element of the array is itself an array or map, and recursively handling them. (This is what's making it a lot of code)
- The object-hash implementation in Node seems to be following the same process as me.
No. Sorry, there is no magic to turn an array into something else. (Actually there is not much magic at all in Go).