Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 295
Sorin Buturugeanu Avatar asked Jul 19 '11 22:07

Sorin Buturugeanu


People also ask

What is the purpose of JSON Stringify () and parse () methods?

The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.

Does JSON Stringify change the object?

JSON. stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object.

What is JSON Stringify and JSON parse?

parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string. Follow this answer to receive notifications.


2 Answers

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.

like image 165
chjj Avatar answered Sep 22 '22 08:09

chjj


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

like image 29
vadimk Avatar answered Sep 20 '22 08:09

vadimk