-
-
Save mayeaux/e742c2a82623eee7b6c74989c773484b 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 hidden or 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 hidden or 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'; } | |
| // } | |
| // }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then how do you turn it back into a JS object again?