Skip to content

Instantly share code, notes, and snippets.

@kresnasatya
Created September 19, 2018 06:02
Show Gist options
  • Save kresnasatya/aaf7cae7ef6759d02b5d0880cc444f0d to your computer and use it in GitHub Desktop.
Save kresnasatya/aaf7cae7ef6759d02b5d0880cc444f0d to your computer and use it in GitHub Desktop.
cheatsheet parsing query string to json and vice versa in JS
function QueryStringToJSON(value) {
var pairs = value.split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.parse(JSON.stringify(result));
}
var json = QueryStringToJSON("key1=value1&key2=value2&key3=value3");
console.log(json)
function JSONToQueryString(value) {
return Object.keys(value).map(key => key + '=' + value[key]).join('&');
}
var query_string = JSONToQueryString(json);
console.log(query_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment