Reputation: 657
I'm trying to hash an array of JSON objects but for some reason the generated hasd doesn't change in some circumstances.
These examples were tested in nodejs by using the sha256 hashing algorithm package.
arr1 = [{a: 1}];
sha(arr1);
'6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d'
arr2 = [{a: 1, b:2}]
sha(arr2);
'6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d'
arr3 = [{a: 1111111111111}];
sha(arr3);
'6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d'
As yo can see all arrays has the same hash generated value even when they has different properties.
arr4 = [{a: 1}, {b: 2}];
sha(arr4);
'96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7'
This one has a different hash because it has two objects instead of only one.
So my question is about to understand what is wrong with the first three arrays if I need to get a different hash of each one.
Upvotes: 0
Views: 710
Reputation: 137161
Your sha()
method probably expects a String and will thus typecast your objects to String:
arr1 = [{a: 1}];
sha(arr1);
arr2 = [{a: 1, b:2}]
sha(arr2);
arr3 = [{a: 1111111111111}];
sha(arr3);
arr4 = [{a: 1}, {b: 2}];
sha(arr4);
function sha(v) {
console.log(v.toString());
}
So if you want an hash from these objects, you'd have to convert these to string correctly, e.g by encoding them to JSON strings first.
Upvotes: 2