Last active
October 7, 2016 14:08
-
-
Save ali-master/a8e9b391c25979ea418db7713062ab23 to your computer and use it in GitHub Desktop.
Convert Query to JSON
This file contains hidden or 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
// <refrence path="https://jsfiddle.net/dm1ufzz3/" /> | |
function QueryStringToJSON(str) { | |
var pairs = str.split('&'); | |
var result = {}; | |
pairs.forEach(function (pair) { | |
pair = pair.split('='); | |
var name = pair[0] | |
var value = pair[1] | |
if (name.length) | |
if (result[name] !== undefined) { | |
if (!result[name].push) { | |
result[name] = [result[name]]; | |
} | |
result[name].push(value || ''); | |
} else { | |
result[name] = value || ''; | |
} | |
}); | |
return result; | |
} | |
var string = 'var1=5&var2=stackoverflow&var3=blah'; | |
var obj = new QueryStringToJSON(string); | |
console.log(obj) // {var1: "5", var2: "stackoverflow", var3: "blah"} |
This file contains hidden or 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
// <refrence path="http://jsfiddle.net/jAGN5/" /> | |
var params = new getUrlVars('some=params&over=here'); | |
console.log(params) | |
function getUrlVars(url) { | |
var hash; | |
var myJson = {}; | |
var hashes = url.slice(url.indexOf('?') + 1).split('&'); | |
for (var i = 0; i < hashes.length; i++) { | |
hash = hashes[i].split('='); | |
myJson[hash[0]] = hash[1]; | |
} | |
return myJson; | |
} |
This file contains hidden or 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
function QueryStringToJSON() { | |
var pairs = location.search.slice(1).split('&'); | |
var result = {}; | |
pairs.forEach(function(pair) { | |
pair = pair.split('='); | |
result[pair[0]] = decodeURIComponent(pair[1] || ''); | |
}); | |
return JSON.parse(JSON.stringify(result)); | |
} | |
var query_string = new QueryStringToJSON(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment