[removed].search query as JSON

2019-02-01 12:58发布

Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.

var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });

9条回答
趁早两清
2楼-- · 2019-02-01 13:32

Probably the shortest solution for simple cases:

location.search
  .slice(1)
  .split('&')
  .map(p => p.split('='))
  .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});
查看更多
一夜七次
3楼-- · 2019-02-01 13:33

My approach, simple and clean

var params = "?q=Hello World&c=Awesome";

params = "{\"" + 
         params
         .replace( /\?/gi, "" )
         .replace( /\&/gi, "\",\"" )
         .replace( /\=/gi, "\":\"" ) +
         "\"}";
  
params = JSON.parse( params );

alert( decodeURIComponent( params.q ) );
alert( decodeURIComponent( params.c ) );

查看更多
我想做一个坏孩纸
4楼-- · 2019-02-01 13:42

JSON Parse after stringify does the job of converting to a json with array data.

?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&

{
     'key1' : 'val1',
     'key2' : [ 'val2.1', 'val2.2', 'val2.3' ]
}

function QueryParamsToJSON() {            
    var list = location.search.slice(1).split('&'),
        result = {};

    list.forEach(function(keyval) {
        keyval = keyval.split('=');
        var key = keyval[0];
        if (/\[[0-9]*\]/.test(key) === true) {
            var pkey = key.split(/\[[0-9]*\]/)[0];
            if (typeof result[pkey] === 'undefined') {
                result[pkey] = [];
            }
            result[pkey].push(decodeURIComponent(keyval[1] || ''));
        } else {
            result[key] = decodeURIComponent(keyval[1] || '');
        }
    });

    return JSON.parse(JSON.stringify(result));
}

var query_string = QueryParamsToJSON();

查看更多
登录 后发表回答