Is JSON.stringify() deterministic in V8?

前端 未结 4 873
梦谈多话
梦谈多话 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:07

    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}'
    

提交回复
热议问题