Tried to find how to make {foo:\"bar\"}
from ?...&foo=bar&...
but googled and got only to jQuery.params
which does the opposit
Actually the above answer by @talsibony doesn't take into account query string arrays (such as test=1&test=2&test=3&check=wow&such=doge
). This is my implementation:
function queryStringToJSON(qs) {
qs = qs || location.search.slice(1);
var pairs = qs.split('&');
var result = {};
pairs.forEach(function(p) {
var pair = p.split('=');
var key = pair[0];
var value = decodeURIComponent(pair[1] || '');
if( result[key] ) {
if( Object.prototype.toString.call( result[key] ) === '[object Array]' ) {
result[key].push( value );
} else {
result[key] = [ result[key], value ];
}
} else {
result[key] = value;
}
});
return JSON.parse(JSON.stringify(result));
};