Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: stringify object (including members of type function)

Tags:

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.

like image 599
Yannick Deltroo Avatar asked Sep 10 '10 15:09

Yannick Deltroo


People also ask

How do you Stringify an object in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Can you Stringify a function in JavaScript?

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Does JSON Stringify work on nested objects?

stringify does not stringify nested arrays. Bookmark this question. Show activity on this post.

Does JSON Stringify preserve functions?

To be clear, the output looks like JSON but in fact is just javascript. JSON. stringify works well in most cases, but "fails" with functions.


1 Answers

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; }); 
like image 104
CD.. Avatar answered Oct 03 '22 17:10

CD..