...

View Full Version : Serialize JS Object to Cookie



CSTruter
08-08-2006, 12:58 PM
Is there a quick way to serialize any javasript object?

Else I have to write a lot of dodgy code to serialize my objects, *sigh* - Cause Writing a serializer will be very easy, but
isnt there a quick way of doing this?

jkd
08-08-2006, 06:41 PM
Gecko-based browsers have a toSource() method that can operate on primitive objects. It appears that Opera doesn't have it though, so I'm assuming other browsers don't as well. If you only need Gecko-compatibility, then that's your ticket. Otherwise, you should probably take advantage of dynamic dispatch:



Object.prototype.serialize = function() {
var response = "{";
for (var p in this) {
if (this.hasOwnProperty(p))
response += p + ":" + this[p].serialize() + ",";
}
return response.substr(0, response.length-1) + "}";
}

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

Number.prototype.serialize = function() {
return this;
}
String.prototype.serialize = function() {
return this;
}
Boolean.prototype.serialize = function() {
return this;
}
Function.prototype.serialize = function() {
return this.toString();
}

// etc

CSTruter
08-08-2006, 07:54 PM
Ah well, I wrote a small piece of code that serializes objects.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum