0

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.

wilson
  • 627
  • 2
  • 11
  • 24
  • 1
    it would be helpful to know what package (or internal) is providing your sha function – rlemon Oct 12 '18 at 02:55
  • 1
    I bet it’s just actually doing sha('[object object]') or whatever the generic string representation of an object is. Like maybe you should turn your objects into json before hashing. – Nate Oct 12 '18 at 03:58

1 Answers1

2

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.

Kaiido
  • 123,334
  • 13
  • 219
  • 285