[removed].search query as JSON

后端 未结 10 826
北海茫月
北海茫月 2020-12-24 14:51

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.



        
相关标签:
10条回答
  • 2020-12-24 15:31

    Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)

    function searchToObject() {
      var pairs = window.location.search.substring(1).split("&"),
        obj = {},
        pair,
        i;
    
      for ( i in pairs ) {
        if ( pairs[i] === "" ) continue;
    
        pair = pairs[i].split("=");
        obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
      }
    
      return obj;
    }
    

    On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)

    0 讨论(0)
  • 2020-12-24 15:39

    If you are using modern browser this produce the same result as accepted answer:

    function searchToObject(search) {
      return search.substring(1).split("&").reduce(function(result, value) {
        var parts = value.split('=');
        if (parts[0]) result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
        return result;
      }, {})
    }
    
    0 讨论(0)
  • 2020-12-24 15:39

    Just wanted to share this solution using a bit of ESNext and a reducer.

    It does pretty much the same suggested by @Carlo but it's a bit cleaner if you're comfortable with ES6 and reducers.

    const urlSearchData = searchString => {
        if (!searchString) return false;
    
        return searchString
            .substring(1)
            .split('&')
            .reduce((result, next) => {
                let pair = next.split('=');
                result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    
                return result;
            }, {});
    };
    
    const searchData = urlSearchData(window.location.search);
    
    0 讨论(0)
  • 2020-12-24 15: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();

    0 讨论(0)
  • 2020-12-24 15:44

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

    0 讨论(0)
  • 2020-12-24 15:50

    Please also note that there's an api to query/manipulate search params with: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

    var params = new URLSearchParams(window.location.search)
    for (let p of params) {
      console.log(p);
    }
    
    0 讨论(0)
提交回复
热议问题