Skip to content

Instantly share code, notes, and snippets.

@cbertelegni
Last active May 26, 2016 15:08
Show Gist options
  • Save cbertelegni/bb8fc7831219be8b39a1f8b32d813052 to your computer and use it in GitHub Desktop.
Save cbertelegni/bb8fc7831219be8b39a1f8b32d813052 to your computer and use it in GitHub Desktop.
Params to json javascript: Convert search/hash location url to json - params to json javascript

Params hash or search to json javascript

Convert search/hash location url to json - params to json javascript

URL Example: example.com/some_page.html#bar=some+value&bar2=value+2&bar3%5B%5D=1&bar3%5B%5D=2&bar3%5B%5D=3&bar3%5B%5D=4

var _hash = location.hash;
// "#bar=some+value&bar2=value+2&bar3%5B%5D=1&bar3%5B%5D=2&bar3%5B%5D=3&bar3%5B%5D=4"
var obj = paramToObj(_hash);
// {bar:"some value", bar2: "value 2", bar3: [1,2,3,4]}
/** convert search/hash location url to json */
function paramToObj (u){
var r = {};
if(u){
u = decodeURIComponent(u.replace(/\?|\#/g,"")).split(/\&/);
u.forEach(function(c, i){
c = c.split("=");
var key = c[0].toLowerCase();
var value = c[1];
if(/^(null|false|true|[0-9]+)$/.test(value)){
value = JSON.parse(value);
}
if ( key.match(/\[\]/g)){
key = key.replace(/\[\]/g, "");
if(!r[key]){
r[key] = [];
}
r[key].push(value);
}else{
r[key] = value;
}
});
}
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment