Skip to content

Instantly share code, notes, and snippets.

@psiborg
Created January 6, 2012 08:45
Show Gist options
  • Select an option

  • Save psiborg/1569753 to your computer and use it in GitHub Desktop.

Select an option

Save psiborg/1569753 to your computer and use it in GitHub Desktop.
JS Serialize
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