Created
January 14, 2014 10:17
-
-
Save dun4n/8416192 to your computer and use it in GitHub Desktop.
Serialize / Deserialize literal object.
This file contains 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 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