JSON.stringify function

Viewed 46684

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

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

and I have to pass this object to another function. So I tried to use JSON.stringify(obj) but the load function (which of course isn't empty, this is just for the purpose of this example) is being "lost".

Is there any way to stringify and object and maintain the methods it has?

Thanks!

6 Answers

You can override the toJSON() method, which serializes the function to another object. Here is an example which converts the function to a string:

Function.prototype.toJSON = Function.prototype.toString;
var o = {name: "FirstName",
age: "19",
load: function () {},
uniq: 0.5233059714082628};

console.log(JSON.stringify(o,null,4))

If you wanted to print, say, the property descriptors instead:

Function.prototype.toJSON = function() {
    return Object.getOwnPropertyDescriptors(this);
}

var o = {name: "FirstName",
age: "19",
load: function () {},
uniq: 0.5233059714082628};

console.log(JSON.stringify(o,null,4))

Related