I\'ve not seen (yet?) JSON.stringify
to be non-deterministic in Node.JS.
There is no guarantee it to be deterministic on the specification level.
In case anyone would look for a function that'll make the JSON dump predictable, I wrote one:
const sortObj = (obj) => (
obj === null || typeof obj !== 'object'
? obj
: Array.isArray(obj)
? obj.map(sortObj)
: Object.assign({},
...Object.entries(obj)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
.map(([k, v]) => ({ [k]: sortObj(v) }),
))
);
Here's a composed deterministic JSON dump:
const deterministicStrigify = obj => JSON.stringify(deterministic(sortObj))
It works well with the examples above:
> obj1 = {};
> obj1.b = 5;
> obj1.a = 15;
> obj2 = {};
> obj2.a = 15;
> obj2.b = 5;
> deterministicStrigify(obj1)
'{"a":15,"b":5}'
> deterministicStrigify(obj2)
'{"a":15,"b":5}'
> JSON.stringify(obj1)
'{"b":5,"a":15}'
> JSON.stringify(obj2)
'{"a":15,"b":5}'