Created
January 6, 2012 08:45
-
-
Save psiborg/1569753 to your computer and use it in GitHub Desktop.
JS Serialize
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
| var serialize = function (obj) { | |
| "use strict"; | |
| var val, vArr, vObj, i, attr; | |
| if (obj !== undefined) { | |
| switch (obj.constructor) { | |
| case "Array": | |
| vArr = "["; | |
| for (i = 0; i < obj.length; i += 1) { | |
| if (i > 0) { | |
| vArr += ","; | |
| } | |
| vArr += this.serialize(obj[i]); | |
| } | |
| vArr += "]"; | |
| return vArr; | |
| case "String": | |
| val = '"' + obj + '"'; | |
| return val; | |
| case "Number": | |
| val = isFinite(obj) ? obj.toString() : null; | |
| return val; | |
| case "Date": | |
| val = "#" + obj + "#"; | |
| return val; | |
| default: | |
| if (typeof obj === "object") { | |
| vObj = []; | |
| for (attr in obj) { | |
| //console.warn(attr, typeof obj[attr], obj[attr]); | |
| if (obj.hasOwnProperty(attr)) { | |
| if (attr === "elems") { | |
| vObj.push('"' + attr + '": ["' + obj[attr].id + '"]'); | |
| } | |
| else if (typeof obj[attr] !== "function") { | |
| if (typeof obj[attr] === "object" || typeof obj[attr] === "number") { | |
| vObj.push('"' + attr + '": ' + this.serialize(obj[attr])); | |
| } | |
| else { | |
| vObj.push('"' + attr + '": "' + this.serialize(obj[attr]) + '"'); | |
| } | |
| } | |
| } | |
| } | |
| if (vObj.length > 0) { | |
| return "{" + vObj.join(",") + "}"; | |
| } | |
| else { | |
| return "{}"; | |
| } | |
| } | |
| else { | |
| return obj.toString(); | |
| } | |
| } | |
| } | |
| return null; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment