Deserialize query string to JSON object

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

    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"}
    
    0 讨论(0)
提交回复
热议问题