How to deterministically verify that a JSON object hasn't been modified?

前端 未结 8 1746
忘了有多久
忘了有多久 2020-11-30 04:38

According to MDN documentation for JSON.stringify:

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 05:13

    Here's an implementation of a deterministic JSON.stringify() that I wrote (uses Underscore.js). It converts (non-array) objects recursively into sorted key-value pairs (as Arrays), then stringifies those. Original coderwall post here.

    Stringify:

    function stringify(obj) {
      function flatten(obj) {
        if (_.isObject(obj)) {
          return _.sortBy(_.map(
              _.pairs(obj),
              function(p) { return [p[0], flatten(p[1])]; }
            ),
            function(p) { return p[0]; }
          );
        }
        return obj;
      }
      return JSON.stringify(flatten(obj));
    }
    

    Parse:

    function parse(str) {
      function inflate(obj, pairs) {
         _.each(pairs, function(p) {
          obj[p[0]] = _.isArray(p[1]) ?
            inflate({}, p[1]) :
            p[1];
        });
        return obj;
      }
      return inflate({}, JSON.parse(str));
    }
    

提交回复
热议问题