Is JSON.stringify() deterministic in V8?

前端 未结 4 861
梦谈多话
梦谈多话 2021-02-19 02:27

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.

4条回答
  •  被撕碎了的回忆
    2021-02-19 03:05

    If by "deterministic" you mean enumeration order of the object's properties: that is actually specified, and V8 follows the spec. See https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys. [Edit: this is the answer to your clarified definition, so yes, JSON.stringify is deterministic in that sense.]

    If by "deterministic" you mean "always returns the same string for the same input object", then, well, no :-)

    > var o = { toJSON: function() { return Math.random(); } }
    > JSON.stringify(o);
    < "0.37377773963616434"
    > JSON.stringify(o);
    < "0.8877065604993732"
    

    Proxy objects and the replacer argument to JSON.stringify can also be used to create arbitrary behavior (even though JSON.stringify itself always does the same thing).

    If by "deterministic" you mean something else, please specify.

提交回复
热议问题