JavaScript – Save object with methods as a string

If you use JSON.stringify with a “replacer” function and
JSON.parse with a “reviver” function along with new Function(), you can do it:

I’m not sure I’m following the second (updated) question you have. Once the object is parsed back into an object, why can’t you just initialize the next and final properties to valid objects before calling any of the object’s methods? You can even add tests into that method that checks for the existence of final and next before returning anything.

var myObj = {
        next: null,
        final:[],
        delimiter: '~', 
        header: false,
        step: function (row) {
            var item = {
                'line_code': row.data[0][0],
                'order': row.data[0][1]
            };
            args.config.config.final.push(item);
        },
        complete: function (result) {
            console.log('Reading data completed. Processing.');
            return args.config.config.next(null, args.config.config.final);
        },
        error: function () {
            console.log('There was an error parsing');
        }
    };

// Stringify the object using a replacer function that will explicitly
// turn functions into strings
var myObjString = JSON.stringify(myObj, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});

// Now, parse back into an object with a reviver function to
// test for function values and create new functions from them:
var obj = JSON.parse(myObjString, function(key, val){
  
    // Make sure the current value is not null (is a string)
    // and that the first characters are "function"
    if(typeof val === "string" && val.indexOf('function') === 0){

      // Isolate the argument names list
      var start = val.indexOf("(") + 1;
      var end = val.indexOf(")");     
      var argListString = val.substring(start,end).split(",");
      
      // Isolate the body of the function
      var body = val.substr(val.indexOf("{"), val.length - end + 1);
      
      // Construct a new function using the argument names and body
      // stored in the string:
      return new Function(argListString, body);
      
    } else {
      // Non-function property, just return the value
      return val;
    } 
  }
);

// Test the method:
obj.error(); // 'There was an error parsing' is written to console.

// Examine the object:
console.log(obj);

Leave a Comment

tech