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.
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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.
stringify does not stringify nested arrays. Bookmark this question. Show activity on this post.
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.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With