Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert query string to JSON using jQuery and back to query string [closed]

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']; 
like image 669
Premchandra Singh Avatar asked Dec 19 '13 09:12

Premchandra Singh


1 Answers

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
}
like image 178
Rohan Kumar Avatar answered Oct 26 '22 23:10

Rohan Kumar