-
-
Save dharFr/1010042 to your computer and use it in GitHub Desktop.
$.unserialize [updated] for jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* $.unserialize | |
* | |
* Takes a string in format "param1=value1¶m2=value2" and returns an object { param1: 'value1', param2: 'value2' }. | |
* If the "param1" ends with "[]" the param is treated as an array. | |
* | |
* Parses the value as String, Int or Boolean | |
* @todo: parseFloat could also be useful I guess. | |
* | |
* Example: | |
* | |
* Input: param1=value1¶m2=value2 | |
* Return: { param1 : value1, param2: value2 } | |
* | |
* Input: param1[]=value1¶m1[]=value2 | |
* Return: { param1: [ value1, value2 ] } | |
* | |
* Input: param1[name1]=value1¶m1[name2]=value2 | |
* Return: { param1: {name1 : value1, name2: value2} } | |
*/ | |
(function($){ | |
function parseValue(strVal) { | |
return ( strVal.match(/^[0-9]+$/) ) ? parseInt(strVal) : (strVal == 'true') ? true : (strVal == 'false') ? false : strVal.replace(/[+]/g, " ") | |
} | |
$.unserialize = function(serializedString){ | |
var str = decodeURIComponent(serializedString); | |
var pairs = str.split('&'); | |
var obj = {}, p, idx, val, match, key, 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 if (match = idx.match(/([^\[]+)\[([^\]]+)\]$/)) { | |
key = match[1]; | |
val = match[2]; | |
if (!obj[key]) { | |
obj[key] = {} | |
} | |
obj[key][val] = parseValue(p[1]) | |
} | |
else { | |
obj[idx] = parseValue(p[1]) | |
} | |
} | |
return obj; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment