views:

4283

answers:

3

Is there something like serialize/unserialize PHP functions in jQuery?

These functions return a string representations of an array or an object which can than be decoded back into array/object.

http://sk2.php.net/serialize

+3  A: 

Why, yes: jQuery's serialize. To unserialize, you'd have to code a function yourself, esentially splitting the string at the &'s and then the ='s.

Oh but it only works on forms. What if I want to serialize an array I create in javascript code like this - var array = []; ?
Richard Knop
You're correct, it only works on forms -- not on an array. Still, thanks for the two upvotes :)
+4  A: 

jQuery's serialize/serializeArray only works for form elements. I think you're looking for something more generic like this:

http://code.google.com/p/jquery-json/

This plugin makes it simple to convert to and from JSON:

var thing = {plugin: 'jquery-json', version: 2.2};

var encoded = $.toJSON(thing);        
//'{"plugin":"jquery-json","version":2.2}'
var name = $.evalJSON(encoded).plugin;
//"jquery-json" var version =
$.evalJSON(encoded).version;  // 2.2

Most people asked me why I would want to do such a thing, which boggles my mind. Javascript makes it relatively easy to convert from JSON, thanks to eval(), but converting to JSON is supposedly an edge requirement.

This plugin exposes four new functions onto the $, or jQuery object:

  • toJSON: Serializes a javascript object, number, string, or arry into JSON.
  • evalJSON: Converts from JSON to Javascript, quickly, and is trivial.
  • secureEvalJSON: Converts from JSON to Javascript, but does so while checking to see if the source is actually JSON, and not with other Javascript statements thrown in.
  • quoteString: Places quotes around a string, and inteligently escapes any quote, backslash, or control characters.
meder
Thanks that's what I was looking for :)
Richard Knop
Remember that JSON is a subset of Javascript -- if your Javascript object has functions in it then they can't be stored in JSON. If you object just contains hashes/arrays/data then JSON is sufficient.
Stewart Johnson
+1  A: 

I was trying to serialize a form and then save it, and when the user returned to the form unserialize it and repopulate the data. Turns out there is a pretty sweet jQuery plugin for doing this already: jQuery autosave. Maybe this will help out some of you.

Will