Created
September 19, 2018 06:02
-
-
Save kresnasatya/aaf7cae7ef6759d02b5d0880cc444f0d to your computer and use it in GitHub Desktop.
cheatsheet parsing query string to json and vice versa in JS
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(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