JSON.stringify function

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!


There is a way to serialize a function in JS, but you'll have to eval it on the other side and it will also lose access to it's original scope. A way to do it would be:

JSON.stringify(objWithFunction, function(key, val) {
  if (typeof val === 'function') {
    return val + ''; // implicitly `toString` it
  }
  return val;
});

There are some legitimate uses for what you're asking despite what people are posting here, however, it all depends on what you're going to be using this for. There may be a better way of going about whatever it is you're trying to do.


In fact, It's very easy to serealize / parse javascript object with methods.

Take a look at JSONfn plugin.

http://www.eslinstructor.net/jsonfn/

Hope this helps.

-Vadim


Why exactly do you want to stringify the object? JSON doesn't understand functions (and it's not supposed to). If you want to pass around objects why not do it one of the following ways?

var x = {name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628};

function y(obj) {
    obj.load();
}

// works
y({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628});

// "safer"
y(({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628}));

// how it's supposed to be done
y(x);