Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Serialize Object in Javascript

5.00/5 (6 votes)
9 Dec 2009CPOL 20.6K  
function serialize(obj) { var returnVal; if(obj != undefined){ switch(obj.constructor) { case Array: var vArr=[; for(var i=0;i<obj.length;i++) { if(i>0) vArr += ,; vArr += serialize(obj[i]); } vArr += ] return vArr; case...
function serialize(obj)
	{
		var returnVal;
		if(obj != undefined){
		switch(obj.constructor)
		{
			case Array:
				var vArr="[";
				for(var i=0;i<obj.length;i++)
				{
					if(i>0) vArr += ",";
					vArr += serialize(obj[i]);
				}
				vArr += "]"
				return vArr;
			case String:
				returnVal = escape("'" + obj + "'");
				return returnVal;
			case Number:
				returnVal = isFinite(obj) ? obj.toString() : null;
				return returnVal;				
			case Date:
				returnVal = "#" + obj + "#";
				return returnVal;		
			default:
				if(typeof obj == "object"){
					var vobj=[];
					for(attr in obj)
					{
						if(typeof obj[attr] != "function")
						{
							vobj.push('"' + attr + '":' + serialize(obj[attr]));
						}
					}
						if(vobj.length >0)
							return "{" + vobj.join(",") + "}";
						else
							return "{}";
				}		
				else
				{
					return obj.toString();
				}
		}
		}
		return null;
	}

function will work recursively and return the serialize js object :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)