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.

2
  • 1
    it would be helpful to know what package (or internal) is providing your sha function Commented Oct 12, 2018 at 2: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. Commented Oct 12, 2018 at 3:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.