Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
$.unserialize for jQuery
/**
* $.unserialize
*
* Takes a string in format "param1=value1&param2=value2" and returns an object { param1: 'value1', param2: 'value2' }. If the "param1" ends with "[]" the param is treated as an array.
*
* Example:
*
* Input: param1=value1&param2=value2
* Return: { param1 : value1, param2: value2 }
*
* Input: param1[]=value1&param1[]=value2
* Return: { param1: [ value1, value2 ] }
*
* @todo Support params like "param1[name]=value1" (should return { param1: { name: value1 } })
*/
(function($){
$.unserialize = function(serializedString){
var str = decodeURI(serializedString);
var pairs = str.split('&');
var obj = {}, p, idx, val;
for (var i=0, n=pairs.length; i < n; i++) {
p = pairs[i].split('=');
idx = p[0];
if (idx.indexOf("[]") == (idx.length - 2)) {
// Eh um vetor
var ind = idx.substring(0, idx.length-2)
if (obj[ind] === undefined) {
obj[ind] = [];
}
obj[ind].push(p[1]);
}
else {
obj[idx] = p[1];
}
}
return obj;
};
})(jQuery);
@CyberShadow

This comment has been minimized.

Copy link

commented May 1, 2011

Won't this break if the value contains an encoded & or =?

@rcmachado

This comment has been minimized.

Copy link
Owner Author

commented May 2, 2011

@CyberShadow

This comment has been minimized.

Copy link

commented May 2, 2011

I don't understand how one implies the other.

$.get('page.php', $.unserialize('foo=bar%3Dbaz'));

This will create a request with a URL like page.php?foo=bar%253Dbaz. Special characters will be encoded twice.

@Komalbandi

This comment has been minimized.

Copy link

commented Jun 17, 2013

Nice.

@er1z

This comment has been minimized.

Copy link

commented Aug 27, 2013

Think should be faster:

if (idx.constructor==[].constructor)

instead of

if (idx.indexOf("[]") == (idx.length - 2)) {
@brucekirkpatrick

This comment has been minimized.

Copy link

commented Oct 17, 2013

There are 2 bugs in this one, which I forked to fix: https://gist.github.com/brucekirkpatrick/7026682
Bug 1: the values were not unescaped. Bug 2: If you had 2 field names with the same name that didn't use the bracket naming convention, the extra values would be lost, they should become an array or at least a comma separated string. I choose array. Here is code to demonstrate the problems:
console.log($.unserialize("one="+escape("& = ?")+"&two="+escape("value1")+"&two="+escape("value2")+"&three[]="+escape("value1")+"&three[]="+escape("value2")+"&three[]="+escape("value3")));

@luislobo14rap

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.