Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jun 2006
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Serialize JS Object to Cookie

    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?
    Last edited by CSTruter; 08-08-2006 at 01:12 PM.

  • #2
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    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:

    Code:
    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

  • #3
    New Coder
    Join Date
    Jun 2006
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    mmm

    Ah well, I wrote a small piece of code that serializes objects.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •