Sunday, September 17, 2006

A very simple serialization for arrays in javascript.

While developing a google module, I had to store an array of strings in a single string.

To do that, since I'm lazy and I didn't want to learn Json or similar stuff,
I came out with a simple trick (that I guess it is already been rediscovered 10.000 times).

Here it is. Suppose you want to achieve the following:


var a = new Array();
a[0] = "x123";
a[1] = "y";
a[2] = "z";
// ...
serialize( a ); // returns: " 'x123','y','z' "
var b = eval( " new Array " + a.serialize() );

Then your serialize method could simply store your array as its own declaration, then use eval to execute the declaration and clone your array.
A simple trick, but it works :)


Try this script:



Array.prototype.serialize =
function (){
var s="("
for (var i=0;i < this.length;i++){
s += "'" + this[i] + "'"
if (i < this.length-1)
s += ","
}
s += ");"
return s
}

var a = new Array();
a[0] = "x123";
a[1] = "y";
a[2] = "z";

var b = eval( " new Array " + a.serialize() );

document.write("original array: "+a );
document.write(" de-serialized array: "+b );




No comments:

Post a Comment