Click here to Skip to main content
12,350,605 members (23,600 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

12K views
2 bookmarked
Posted

Serialize Object in Javascript

, 8 Dec 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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 Smile | :)

License

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

Share

About the Author

Mehul M Thakkar
Technical Lead
India India
Mehul Thakkar is having 8 yrs of experience in IT industry. He is having good command over Ms .Net and Ms Sql Server

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160621.1 | Last Updated 9 Dec 2009
Article Copyright 2009 by Mehul M Thakkar
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid