Serialize Object in JavaScript

Mehulthakkar1
Posted by in JavaScript category on for Beginner level | Views : 37874 red flag
Rating: 5 out of 5  
 1 vote(s)

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.

Page copy protected against web site content infringement by Copyscape

About the Author

Mehulthakkar1
Full Name: Mehul Thakkar
Member Level:
Member Status: Member
Member Since: 10/8/2009 11:06:06 PM
Country:


System Analyst Mehul Thakkar

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)