Created
October 19, 2016 19:20
-
-
Save Lepozepo/3275d686bc56e4fb5d11d27ef330a8ed to your computer and use it in GitHub Desktop.
Stringify and revive with functions
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
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