11

Hope you will find following function useful for converting query string into json object

var queryStringToJSON = function (url) {
    if (url === '')
        return '';
    var pairs = (url || location.search).slice(1).split('&');
    var result = {};
    for (var idx in pairs) {
        var pair = pairs[idx].split('=');
        if (!!pair[0])
            result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
    }
    return result;
}

Usage:

To get current windows query string

var result = queryStringToJSON() // without any parameter

To get json from custom query string:

var result = queryStringToJSON('?name=prem&age=30&HEIGHT=5.8')

output: {name:"prem", age:"30", height:"5.8"} //All keys are converted into small letters

To convert it back to url you can use jQuery param method

$.param(result)

To manipulate your query string you can simple use standard object manipulation in JavaScript and use $.param method again

result.age=35;
delete result['name']; 
4
  • 3
    So what's your question? Commented Dec 19, 2013 at 9:32
  • he just posted his useful function to help others... so no question here... Commented Dec 19, 2013 at 9:33
  • 1
    Then why did I find this in "questions" section? Commented Dec 19, 2013 at 9:34
  • This does not seem to be working with array's: eg: ?=name=Tom&name=Jeff Commented May 27, 2014 at 12:21

2 Answers 2

1

Working, but if you used url || location.search then you should remove if(url === '') return '' or it should be like,

var queryStringToJSON = function (url) {
    url = url || location.search;// url or location.search
    if (url === '')
        return '';// return if url and location.search not found
    // your remainig code
}
2
  • Understood but this is a special check. '' is special falsy value in string manipulation. So I just want a check if falsy value is empty string just return as it is. Commented Dec 19, 2013 at 9:46
  • Then you should not use location.search in line var pairs = (url || location.search).slice(1).split('&'); Commented Dec 19, 2013 at 9:56
1

Alternatively... Instead of:

for (var idx in pairs) {
    var pair = pairs[idx].split('=');
    if (!!pair[0])
        result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
}

Try:

result = pairs.reduce(function(a,b) {
     var pair = b.split("=");
     a[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
     return a;
},{});

Works the same but uses reduce() which being a native javascript function, is probably faster.

1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.