1

Can I compare two identical data-only objects from two different JS engines that are converted to strings using JSON.stringify?

Will they have different amounts of white space/escape characters/orders, or be identical character for character?

Does the JS language spec define a exact standard for JSON.stringify'd data?

Im only interested in modern JS engines (2016+).

4
  • My instinct is to say, yes, the handling would be identical, though I have no link to back this up. Commented Jul 11, 2017 at 12:17
  • 1
    why you ask though ? Commented Jul 11, 2017 at 12:18
  • 3
    Since the order of properties in an object is inherently not guaranteed to be ordered/stable, as soon as you're encoding any objects I would absolutely not count on it whatsoever. Even otherwise, I would not count on it. There are several different ways in which the same value can legally be encoded in JSON, and engines may change the details for whatever reason at any time. It's simply not a spec to depend on. Guaranteed uniformity is not a goal of the JSON spec. Commented Jul 11, 2017 at 12:21
  • 1
    The call also allows for provision of a spacing argument so how it's called would matter. Commented Jul 11, 2017 at 12:23

2 Answers 2

3

According to MDN (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)

JSON.stringify() converts a value to JSON notation representing it:

  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
Sign up to request clarification or add additional context in comments.

4 Comments

Does this mean it would be OK for an array of strings?
@zino, yes in my understanding element of an array would get stringified in the same order and if you use the space parameter you can enforce the same output.
As of now, 01.01.2023 there is no such sentence at MDN page of JSON.stringify. Even more, is says that: "Properties are visited using the same algorithm as Object.keys(), which has a well-defined order and is stable across implementations. For example, JSON.stringify on the same object will always produce the same string"
@Sergey true. Here is when it was changed github.com/mdn/content/issues/16583
-1

You can use fastest-stable-stringify to predictably stringify your JSON.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.