JSON.stringify function

后端 未结 5 897
谎友^
谎友^ 2020-11-27 04:56

I have an object that has some properties and methods, like so:

{name: \"FirstName\",
age: \"19\",
load: function () {},
uniq: 0.5233059714082628}

5条回答
  •  生来不讨喜
    2020-11-27 05:32

    Here's some code I have used in my previous projects, maybe useful?

      // Similar to JSON.stringify(), with three major differences:
      // (1) It also wrap functions
      // (2) Upon execution, it expose an object, nl, into the scope
      // (3) Results are minified by 'uglify-js'
      var bundle = function(obj) {
        var type = typeof obj;
        if(type === 'string') return '\'' + obj + '\'';
        if(type === 'boolean' || type === 'number') return obj;
        if(type === 'function') return obj.toString();
        var ret = [];
        for(var prop in obj) {
          ret.push(prop + ': ' + bundle(obj[prop]));
        }
        return '{' + ret.join(',') + '}';
      };
      var ret = 'var nl = ' + bundle(nl);
      ret = require('uglify-js').minify(ret, {fromString: true}).code;
      fs.writeFileSync('nl.js', ret);
    

    One Caveat when using this is that if the function uses anything in external closure, it won't work, ie: ... obj: {..., key: (function() {...var a = 10;... return function() {... some code uses 'a'...})()}

提交回复
热议问题