There are many plugins for deserializing form data in json format, however there is a profound lack of plugins for turning native objects in javascript into serialized JSON objects. There is a plugin at json.org but frankly , it stinks- memory leaks in IE and its 3 times as long as the equivalent code here which doesn't even use any jquery helpers for serializing.11
jQuery.box=function(obj) {
var ret="";
if (typeof(obj)!='object') {
return typeof(obj)=='string'?"'"+obj+"'":new String(obj);
} else if ((typeof(obj)!='function')&&(obj!=null)) {
try {
var o=obj.constructor==Object?'{':'[';
var c=o=='{'?'}':']';
var kvs=[];
if (o=='{')
for (i in obj) {
kvs.push("'"+i+"':"+$.box(obj[i]));
}
else
for (i=0;i<obj.length;kvs.push($.box(obj[i++])));
} catch(e) {
return "{'error':'"+e.message.replace(/'/g,"`")+"'}";
}
return o+kvs.join(',')+c;
} else {
return 'null';
}
};
Feel free to modify / improve upon this code and repost as you with, note that I originally came up with it though.