Javascript: stringify object (including members of type function) Javascript: stringify object (including members of type function) json json

Javascript: stringify object (including members of type function)


You can use JSON.stringify with a replacer like:

JSON.stringify({   color: 'red',   doSomething: function (arg) {        alert('Do someting called with ' + arg);   }}, function(key, val) {        return (typeof val === 'function') ? '' + val : val;});


A quick and dirty way would be like this:

Object.prototype.toJSON = function() {  var sobj = {}, i;  for (i in this)     if (this.hasOwnProperty(i))      sobj[i] = typeof this[i] == 'function' ?        this[i].toString() : this[i]; return sobj;};

Obviously this will affect the serialization of every object in your code, and could trip up niave code using unfiltered for in loops. The "proper" way would be to write a recursive function that would add the toJSON function on all the descendent members of any given object, dealing with circular references and such. However, assuming single threaded Javascript (no Web Workers), this method should work and not produce any unintended side effects.

A similar function must be added to Array's prototype to override Object's by returning an array and not an object. Another option would be attaching a single one and let it selectively return an array or an object depending on the objects' own nature but it would probably be slower.

function JSONstringifyWithFuncs(obj) {  Object.prototype.toJSON = function() {    var sobj = {}, i;    for (i in this)       if (this.hasOwnProperty(i))        sobj[i] = typeof this[i] == 'function' ?          this[i].toString() : this[i];    return sobj;  };  Array.prototype.toJSON = function() {      var sarr = [], i;      for (i = 0 ; i < this.length; i++)           sarr.push(typeof this[i] == 'function' ? this[i].toString() : this[i]);      return sarr;  };  var str = JSON.stringify(obj);  delete Object.prototype.toJSON;  delete Array.prototype.toJSON;  return str;}

http://jsbin.com/yerumateno/2/edit


Something like this...

(function(o) {    var s = "";    for (var x in o) {        s += x + ": " + o[x] + "\n";    }    return s;})(obj)

Note: this is an expression. It returns a string representation of the object that is passed in as an argument (in my example, I'm passing the in an variable named obj).

You can also override the toString method of the Object's prototype:

Object.prototype.toString = function() {    // define what string you want to return when toString is called on objects}