Deserialize query string to JSON object

后端 未结 7 1219
感情败类
感情败类 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:05

    In modern browsers, you can also use Object.fromEntries which makes this even easier.

    function queryStringToObject(queryString) {
      const pairs = queryString.substring(1).split('&');
      // → ["foo=bar", "baz=buzz"]
    
      var array = pairs.map((el) => {
        const parts = el.split('=');
        return parts;
      });
      // → [["foo", "bar"], ["baz", "buzz"]]
    
      return Object.fromEntries(array);
      // → { "foo": "bar", "baz": "buzz" }
    }
    
    console.log(queryStringToObject('?foo=bar&baz=buzz'));


    The URLSearchParams interface can Interactive with the browsers URL search parameters. The browser support for URLSearchParams is pretty decent.

    For your case, it would be:

    console.log(
      Object.fromEntries(new URLSearchParams('foo=bar&baz=buzz'))
    );

    0 讨论(0)
  • 2021-01-04 02:08

    I know this thread is a bit old - but this is what worked for me - hopefully it will help someone else too ..

    var _searchModel = yourquerystring.split("&");
    for (var x = 0; x < _searchModel.length; x++) {
      //break each set into key and value pair
      var _kv = _searchModel[x].split("=");
    
      //console.log(_kv);
    
      var _fieldID = _kv[0];
      var _fieldVal = _kv[1];
    }

    0 讨论(0)
  • 2021-01-04 02:11

    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.

    0 讨论(0)
  • 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));
    };
    
    0 讨论(0)
  • 2021-01-04 02:18

    for simple and flat query strings, something like this will do the trick

    const queryStringToObject = (queryString) => {
      let obj = {}
      if(queryString) {
        queryString.slice(1).split('&').map((item) => {
          const [ k, v ] = item.split('=')
          v ? obj[k] = v : null
        })
      }
      return obj
    }
    
    > queryStringToObject('?foo=bar&baz=buzz')
    { foo: 'bar', baz: 'buzz' }
    
    0 讨论(0)
  • 2021-01-04 02:18

    The URLSearchParams() constructor creates and returns a new URLSearchParams object.

    var url = new URL('https://example.com?foo=1&bar=2'); 
    var params = new URLSearchParams(url.search);
    

    https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

    0 讨论(0)
提交回复
热议问题