1

Since properties order in objects is not guaranteed in JavaScript, how does JSON.stringify() actually behave?

  1. Is the following always true (same object)?

const o = { a: 1, b: 2 };
console.log(JSON.stringify(o) === JSON.stringify(o));
  1. Is the following always true (deeply equal objects, same key declaration order)?

console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ a: 1, b: 2 }));
  1. How to make the following be true (deeply equal objects, different key declaration order)?

console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 }));
sp00m
  • 44,266
  • 23
  • 127
  • 230
  • 1) Yes, the enumeration order on the same object is always guaranteed to be same. 2) It should be, although there's no strict guarantee we would expect determinism. 3) You cannot "make" this true, you should just use [a deep equality predicate function](https://stackoverflow.com/q/201183/1048572) instead comparing `JSON.stringify` results – Bergi Sep 27 '17 at 13:11

1 Answers1

2

I looked at the ECMAScript standard for JSON.stringify: http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3

This seems informative:

For each element P of K.

Let strP be the result of calling the abstract operation Str with arguments P and value.
If strP is not undefined
    Let member be the result of calling the abstract operation Quote with argument P.
    Let member be the concatenation of member and the colon character.
    If gap is not the empty String
        Let member be the concatenation of member and the space character.
    Let member be the concatenation of member and strP.
    Append member to partial.

The "append" in the final step strongly implies that the results are ordered per the source, and I can confirm your code assertions pass on both Chromium and Firefox.

EDIT: For "P of K", this might be relevant too:

The ordering of the Strings should be the same as that used by the Object.keys standard built-in function.

It seems that your assertions are true so long as the comparisons are kept in one browser.

Louis Jackman
  • 961
  • 5
  • 15
  • No. Append means that the string is built in the order of "for each element P of K", it does not mean that they are ordered per source (or whatever that might be for dynamically generated objects). – Bergi Sep 27 '17 at 13:10