Javascript: stringify object (including members of type function)

Viewed 14598

I'm looking for a solution to serialize (and unserialize) Javascript objects to a string across browsers, including members of the object that happen to be functions. A typical object will look like this:

{
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}

doSomething() will only contain local variables (no need to also serialize the calling context!).

JSON.stringify() will ignore the 'doSomething' member because it's a function. I known the toSource() method will do what I want but it's FF specific.

6 Answers

var myObj = {
  color: 'red',
  doSomething: function (arg) {
  alert('Do someting called with ' + arg);
  }
}

var placeholder = '____PLACEHOLDER____';
var fns = [];
var json = JSON.stringify(myObj, function(key, value) {
  if (typeof value === 'function') {
    fns.push(value);
    return placeholder;
  }
  return value;
}, 2);

json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) {
  return fns.shift();
});

console.log(json)

https://gist.github.com/cowboy/3749767

Related