-
-
Save jochemstoel/fa97dbe0da44cce2306f 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'; } | |
// } | |
// }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment