Skip to content

Instantly share code, notes, and snippets.

@Lepozepo
Created October 19, 2016 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lepozepo/3275d686bc56e4fb5d11d27ef330a8ed to your computer and use it in GitHub Desktop.
Save Lepozepo/3275d686bc56e4fb5d11d27ef330a8ed to your computer and use it in GitHub Desktop.
Stringify and revive with functions
function stringifyWithFunctions(object) {
return JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return `(${val})`; // make it a string, surround it by parenthesis to ensure we can revive it as an anonymous function
}
return val;
});
};
function parseWithFunctions(obj) {
return JSON.parse(obj, (k, v) => {
if (typeof v === 'string' && v.indexOf('function') >= 0) {
return eval(v);
}
return v;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment