![]()
Article posted by
Mehulthakkar1 on 1/7/2010 | Views: 32668 | Category:
JavaScript | Level: Beginner
If you found
plagiarised (copied) or inappropriate content,
please
let us know the original source along with your correct email id (to communicate) for further action.
This Article will help you getting the serialized object from javascript.
Introduction
Sometimes while developing application you would have to Serialize/De-serialize the object. With this article once can serialize the object in JavaScript, where the object is created in JavaScript only. But why to Serialize object in JavaScript. The answer is, some times we want to pass the object to web service from JavaScript, it is not possible to perform this. So you can serialize it and send it.
How to serialize an Object
Every JavaScript object/variable has it's own type defined in constructor. You can check that property and identify the type.
var obj = new Array();
alert(obj.constructor);
This will alert "Array" in dialog.
Now lets write the method to serialize the object.
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;
}
Check this "serialize" function, it will accept the parameter of any type and return you serialize object.
var x = new Object();
x.Name = "xyz";
x.Phone = 222222;
x.Email = "mehul@xyz.com";
var y = serialize(x);
alert(y);
This will alert {"Name":'xyz', "Phone":222222, "Email":'mehul@xyz.com'} string in dialog. After serialize it one can send it to server side. The created x object can not be passed directly to the server without serialize it. User can pass any type of varible/object in this method and get the serialize object.
If you like this article, subscribe to our
RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.
Found interesting? Add this to: