Created
September 19, 2012 13:45
-
-
Save cowboy/3749767 to your computer and use it in GitHub Desktop.
JavaScript: like JSON.stringify but handles functions, good for creating arbitrary .js objects?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stringify = function(obj, prop) { | |
var placeholder = '____PLACEHOLDER____'; | |
var fns = []; | |
var json = JSON.stringify(obj, function(key, value) { | |
if (typeof value === 'function') { | |
fns.push(value); | |
return placeholder; | |
} | |
return value; | |
}, 2); | |
json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) { | |
return fns.shift(); | |
}); | |
return 'this["' + prop + '"] = ' + json + ';'; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var foo = { | |
a: function() { return 'a'; }, | |
b: function() { return 'b'; }, | |
'bar.baz': { | |
'omg ponies!!': function() { return 'c'; } | |
} | |
}; | |
console.log(stringify(foo, 'foo')); | |
// this["foo"] = { | |
// "a": function () { return 'a'; }, | |
// "b": function () { return 'b'; }, | |
// "bar.baz": { | |
// "omg ponies!!": function () { return 'c'; } | |
// } | |
// }; |
thanks a lot cowboy, javascript is more than json!
how cool, if you can get to the solution to your current problem with function, share
https://gist.github.com/jspinoza3/1805df875fe168833dddc3f7e1abbad7 ^^handles concise method syntax and fat arrows.
the link is dead, but your code was enough for me now.
This custom stringify function can be handy when you need to serialize JavaScript objects that include functions into strings for storage or transmission, while still retaining the ability to execute that's not my neighbor those functions after deserialization.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just wanted to comment that this function has saved me more than once!