Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize query string to JSON object

Tried to find how to make {foo:"bar"} from ?...&foo=bar&... but googled and got only to jQuery.params which does the opposite. Any suggestions please (built-in javascript function, jQuery, Underscore.js - all goes)? Or, do I need to implement it by myself (not a big hassle, just trying not to reinvent the wheel)?

like image 656
BreakPhreak Avatar asked Jul 19 '12 09:07

BreakPhreak


3 Answers

Actually the above answer by @talsibony doesn't take into account query string arrays (such as test=1&test=2&test=3&check=wow&such=doge). This is my implementation:

function queryStringToJSON(qs) {
    qs = qs || location.search.slice(1);

    var pairs = qs.split('&');
    var result = {};
    pairs.forEach(function(p) {
        var pair = p.split('=');
        var key = pair[0];
        var value = decodeURIComponent(pair[1] || '');

        if( result[key] ) {
            if( Object.prototype.toString.call( result[key] ) === '[object Array]' ) {
                result[key].push( value );
            } else {
                result[key] = [ result[key], value ];
            }
        } else {
            result[key] = value;
        }
    });

    return JSON.parse(JSON.stringify(result));
};
like image 187
Carlo G Avatar answered Oct 08 '22 20:10

Carlo G


I am posting here my function just in case other will look and will want to get it straight forward no need for jquery native JS. Because I was looking for the same thing and finally made this function after viewing others answers:

function queryStringToJSON(queryString) {
  if(queryString.indexOf('?') > -1){
    queryString = queryString.split('?')[1];
  }
  var pairs = queryString.split('&');
  var result = {};
  pairs.forEach(function(pair) {
    pair = pair.split('=');
    result[pair[0]] = decodeURIComponent(pair[1] || '');
  });
  return result;
}


console.log(queryStringToJSON(window.location.href)); 
console.log(queryStringToJSON('test=1&check=wow'));//Object {test: "1", check: "wow"}
like image 42
talsibony Avatar answered Oct 08 '22 22:10

talsibony


You have Ben Alman's jQuery BBQ and a jQuery.deparam in it. It is described as The opposite of jQuery.param, pretty much.

http://benalman.com/code/projects/jquery-bbq/examples/deparam/

First example is exactly what you need.

like image 8
Zagor23 Avatar answered Oct 08 '22 20:10

Zagor23