Created
February 10, 2012 06:29
-
-
Save can3p/1787188 to your computer and use it in GitHub Desktop.
Parse a string serialized by jQuery.param
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
/** | |
* Converts a string that was serialized with jQuery.param back to the object. | |
* | |
* @param {String} str | |
* | |
* @return {Object} | |
*/ | |
function parseParams(str) { | |
var obj = {}, pair; | |
var pairs = decodeURIComponent(str).split( "&" ); | |
var injectParam = function(key, val) { | |
var firstBracket = key.indexOf('['); | |
if (firstBracket === -1) { | |
obj[key] = val; | |
return; | |
} | |
var prevkey = key.substring(0, firstBracket), | |
key = key.substr(firstBracket), | |
prev = obj, | |
newobj, | |
newkey; | |
key.replace(/\[([^\]]+)?\]/g, function(chunk, idx, pos) { | |
var newobj, newkey; | |
if (chunk.match(/\[\d*\]/)) { | |
newobj = prev[prevkey] || []; | |
newkey = idx || '[]'; | |
} else { | |
newobj = prev[prevkey] || {}; | |
newkey = idx; | |
} | |
if (prevkey === '[]') { | |
prev.push(newobj); | |
} else { | |
prev[prevkey] = newobj; | |
} | |
prev = newobj; | |
prevkey = newkey; | |
}); | |
if (prevkey === '[]') { | |
prev.push(val); | |
} else { | |
prev[prevkey] = val; | |
} | |
} | |
//if user passes simple string, we return it as an response | |
if (pairs.length === 1) { | |
return pair[0]; | |
} | |
for( var arg = 0; arg < pairs.length; arg++ ) { | |
pair = pairs[ arg ].split( "=" ); | |
injectParam(pair[0], pair[1]); | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for posting this...I just forked it and enhanced it to also parse old style param where a key may have multiple values...
Thanks again.