Skip to content

Instantly share code, notes, and snippets.

@bingzer
Forked from cowboy/stringify.js
Created February 21, 2021 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bingzer/3a002a57127f50585412da182e79aece to your computer and use it in GitHub Desktop.
Save bingzer/3a002a57127f50585412da182e79aece to your computer and use it in GitHub Desktop.
JavaScript: like JSON.stringify but handles functions, good for creating arbitrary .js objects?
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 + ';';
};
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