Deserialize query string to JSON object

后端 未结 7 1254
感情败类
感情败类 2021-01-04 01:21

Tried to find how to make {foo:\"bar\"} from ?...&foo=bar&... but googled and got only to jQuery.params which does the opposit

7条回答
  •  时光取名叫无心
    2021-01-04 02:15

    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));
    };
    

提交回复
热议问题