Skip to content

Instantly share code, notes, and snippets.

@ajermakovics
Forked from anvaka/gist:3815296
Created February 11, 2014 13:53
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 ajermakovics/8935214 to your computer and use it in GitHub Desktop.
Save ajermakovics/8935214 to your computer and use it in GitHub Desktop.
function functionReplacer(key, value) {
if (typeof(value) === 'function') {
return value.toString();
}
return value;
}
function functionReviver(key, value) {
if (key === "") return value;
if (typeof value === 'string') {
var rfunc = /function[^\(]*\(([^\)]*)\)[^\{]*{([^\}]*)\}/,
match = value.match(rfunc);
if (match) {
var args = match[1].split(',').map(function(arg) { return arg.replace(/\s+/, ''); });
return new Function(args, match[2]);
}
}
return value;
}
var person = {
name : 'John Smith',
age : 42,
isJohn: function() {
return !!this.name.match(/John/);
}
};
jsonString = JSON.stringify(person, functionReplacer);
restoredPerson = JSON.parse(jsonString, functionReviver);
console.log(restoredPerson.isJohn());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment