Skip to content

Instantly share code, notes, and snippets.

@dun4n
Created January 14, 2014 10:17
Show Gist options
  • Save dun4n/8416192 to your computer and use it in GitHub Desktop.
Save dun4n/8416192 to your computer and use it in GitHub Desktop.
Serialize / Deserialize literal object.
function serialize(obj) {
return JSON.stringify(obj, function (key, value) {
return typeof value === 'function' ? value.toString() : value;
})
}
function deserialize(str) {
return JSON.parse(str, function (key, value) {
if (value && typeof value === "string" && value.substr(0,8) == "function") {
var body = value.substring(value.indexOf('{') + 1, value.lastIndexOf('}'))
var args = value.substring(value.indexOf('(') + 1, value.indexOf(')'));
return new Function(args, body);
}
return value;
})
}
/*
$ var person = {
"firstname": "John",
"lastname": "Smith",
"toString": function() { return this.firstname + " " + this.lastname }
};
$ var sperson = serialize(person);
> "{"firstname":"John","lastname":"Smith","toString":"function () { return this.firstname + \" \" + this.lastname }"}"
$ var johnsmith = deserialize(sperson).toString()
> "John Smith"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment