将URL参数转换为JavaScript对象。

时间:2022-01-06 10:31:22

I have a string like this:

我有一个这样的字符串:

abc=foo&def=%5Basf%5D&xyz=5

美国广播公司(abc)= foo&def = % 5巴斯夫% 5 d&xyz = 5

How can I convert it into a JavaScript object like this?

如何将它转换成这样的JavaScript对象?

{
  abc: 'foo',
  def: '[asf]',
  xyz: 5
}

20 个解决方案

#1


209  

Edit

This edit improves and explains the answer based on the comments.

这个编辑改进并根据评论解释了答案。

var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

Example

例子

Parse abc=foo&def=%5Basf%5D&xyz=5 in five steps:

在五个步骤中,解析abc=foo&def=%5Basf%5D&xyz=5:

  • decodeURI: abc=foo&def=[asf]&xyz=5
  • decodeURI:abc = foo&def = xyz(asf)= 5
  • Escape quotes: same, as there are no quotes
  • 转义引号:相同,因为没有引号。
  • Replace &: abc=foo","def=[asf]","xyz=5
  • 取代&:abc = foo”、“def =(asf)”、“xyz = 5
  • Replace =: abc":"foo","def":"[asf]","xyz":"5
  • 取代=:abc”:“foo”、“def”:“(asf)”、“xyz”:“5
  • Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}
  • Suround卷曲和引用:{“abc”:“foo”、“def”:“(asf)”,“xyz”:“5”}

which is legal JSON.

这是合法的JSON。

An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:

改进的解决方案允许搜索字符串中的更多字符。它使用了一个修订函数URI解码:

var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

Example

例子

search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";

gives

给了

Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}

Original answer

A one-liner:

一行程序:

JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')

#2


21  

Split on & to get name/value pairs, then split each pair on =. Here's an example:

分开并获取名称/值对,然后将每一对分开。这里有一个例子:

var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
var obj = str.split("&").reduce(function(prev, curr, i, arr) {
    var p = curr.split("=");
    prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
    return prev;
}, {});

Another approach, using regular expressions:

另一种方法,使用正则表达式:

var obj = {}; 
str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
    obj[decodeURIComponent(key)] = decodeURIComponent(value);
}); 

This is adapted from John Resig's "Search and Don’t Replace".

这是改编自John Resig的“搜索和不要替换”。

#3


11  

This is the simple version, obviously you'll want to add some error checking:

这是一个简单的版本,显然你需要添加一些错误检查:

var obj = {};
var pairs = queryString.split('&');
for(i in pairs){
    var split = pairs[i].split('=');
    obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}

#4


9  

I found $.String.deparam the most complete pre built solution (can do nested objects etc.). Check out the documentation.

我发现$. string .deparam是最完整的预构建解决方案(可以做嵌套对象等)。查看文档。

#5


6  

I had the same problem, tried the solutions here, but none of them really worked, since I had arrays in the URL parameters, like this:

我有同样的问题,尝试过这里的解决方案,但是没有一个真正起作用,因为我在URL参数中有数组,像这样:

?param[]=5&param[]=8&othr_param=abc&param[]=string

So I ended up writing my own JS function, which makes an array out of the param in URI:

所以我最后写了我自己的JS函数,它在URI中创建了一个数组

/**
 * Creates an object from URL encoded data
 */
var createObjFromURI = function() {
    var uri = decodeURI(location.search.substr(1));
    var chunks = uri.split('&');
    var params = Object();

    for (var i=0; i < chunks.length ; i++) {
        var chunk = chunks[i].split('=');
        if(chunk[0].search("\\[\\]") !== -1) {
            if( typeof params[chunk[0]] === 'undefined' ) {
                params[chunk[0]] = [chunk[1]];

            } else {
                params[chunk[0]].push(chunk[1]);
            }


        } else {
            params[chunk[0]] = chunk[1];
        }
    }

    return params;
}

#6


5  

Another solution based on the latest standard of URLSearchParams (https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

基于URLSearchParams最新标准的另一种解决方案(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

function getQueryParamsObject() {
  const searchParams = new URLSearchParams(location.search.slice(1));
  return searchParams
    ? _.fromPairs(Array.from(searchParams.entries()))
    : {};
}

Please note that this solution is making use of

请注意这个解决方案正在使用。

Array.from (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

Array.from(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

and _.fromPairs (https://lodash.com/docs#fromPairs) of lodash for the sake of simplicity.

并且为了简单起见,从lodash对(https://lodash.com/docs# from成对)进行。

It should be easy to create a more compatible solution since you have access to searchParams.entries() iterator.

创建一个更兼容的解决方案应该很容易,因为您可以访问searchParams.entries()迭代器。

#7


3  

Using ES6, URL API and URLSearchParams API.

使用ES6, URL API和URLSearchParams API。

function objectifyQueryString(url) {
  let _url = new URL(url);
  let _params = new URLSearchParams(_url.search);
  let query = Array.from(_params.keys()).reduce((sum, value)=>{
    return Object.assign({[value]: _params.get(value)}, sum);
  }, {});
  return query;
}

#8


2  

There is no native solution that I'm aware of. Dojo has a built-in unserialization method if you use that framework by chance.

我没有意识到本地的解决方案。如果使用这个框架,Dojo有一个内置的非序列化方法。

Otherwise you can implement it yourself rather simply:

否则,你自己就可以简单地实现它:

function unserialize(str) {
  str = decodeURIComponent(str);
  var chunks = str.split('&'),
      obj = {};
  for(var c=0; c < chunks.length; c++) {
    var split = chunks[c].split('=', 2);
    obj[split[0]] = split[1];
  }
  return obj;
}

edit: added decodeURIComponent()

编辑:添加decodeURIComponent()

#9


2  

There's a lightweight library called YouAreI.js that's tested and makes this really easy.

有一个轻量级的库叫做YouAreI。这是经过测试的,这真的很简单。

YouAreI = require('YouAreI')
uri = new YouAreI('http://user:pass@www.example.com:3000/a/b/c?d=dad&e=1&f=12.3#fragment');

uri.query_get() => { d: 'dad', e: '1', f: '12.3' }

#10


2  

A concise solution:

一个简洁的解决方案:

location.search
  .slice(1)
  .split('&')
  .map(p => p.split('='))
  .reduce((obj, pair) => {
    const [key, value] = pair.map(decodeURIComponent);
    return ({ ...obj, [key]: value })
  }, {});

#11


1  

Here's one I use:

这是一个我使用:

var params = {};
window.location.search.substring(1).split('&').forEach(function(pair) {
  pair = pair.split('=');
  if (pair[1] !== undefined) {
    var key = decodeURIComponent(pair[0]),
        val = decodeURIComponent(pair[1]),
        val = val ? val.replace(/\++/g,' ').trim() : '';

    if (key.length === 0) {
      return;
    }
    if (params[key] === undefined) {
      params[key] = val;
    }
    else {
      if ("function" !== typeof params[key].push) {
        params[key] = [params[key]];
      }
      params[key].push(val);
    }
  }
});
console.log(params);

Basic usage, eg.
?a=aa&b=bb
Object {a: "aa", b: "bb"}

基本用法,例如。a:“aa”,b:“bb”

Duplicate params, eg.
?a=aa&b=bb&c=cc&c=potato
Object {a: "aa", b: "bb", c: ["cc","potato"]}

重复的参数,例如。? = aa&b = bb&c = cc&c =土豆对象{“aa”,b:“bb”,c:[“cc”、“土豆”]}

Missing keys, eg.
?a=aa&b=bb&=cc
Object {a: "aa", b: "bb"}

丢失的钥匙,如。a: "aa", b: "bb"}

Missing values, eg.
?a=aa&b=bb&c
Object {a: "aa", b: "bb"}

缺失值,例如。a: "aa", b: "bb"}

The above JSON/regex solutions throw a syntax error on this wacky url:
?a=aa&b=bb&c=&=dd&e
Object {a: "aa", b: "bb", c: ""}

上面的JSON/regex解决方案在这个古怪的url上抛出一个语法错误:?a=aa&b=bb&c=&=dd&e对象{a:“aa”,b:“bb”,c:“}”

#12


1  

Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc):

这是我的快速和不干净的版本,主要是将“&”分隔的URL参数分解为数组元素,然后遍历该数组,并将“=”分隔的键/值对添加到一个对象中。我使用decodeURIComponent()将已编码的字符转换为它们的普通字符串等效项(因此%20变成一个空格,%26变成'&'等):

function deparam(paramStr) {
    let paramArr = paramStr.split('&');     
    let paramObj = {};
    paramArr.forEach(e=>{
        let param = e.split('=');
        paramObj[param[0]] = decodeURIComponent(param[1]);
    });
    return paramObj;
}

example:

例子:

deparam('abc=foo&def=%5Basf%5D&xyz=5')

returns

返回

{
    abc: "foo"
    def:"[asf]"
    xyz :"5"
}

The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.

唯一的问题是xyz是一个字符串,而不是一个数字(由于使用了decodeURIComponent()),但除此之外,它还不是一个不好的起点。

#13


1  

//under ES6 
const getUrlParamAsObject = (url = window.location.href) => {
    let searchParams = url.split('?')[1];
    const result = {};
    //in case the queryString is empty
    if (searchParams!==undefined) {
        const paramParts = searchParams.split('&');
        for(let part of paramParts) {
            let paramValuePair = part.split('=');
            //exclude the case when the param has no value
            if(paramValuePair.length===2) {
                result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
            }
        }

    }
    return result;
}

#14


1  

Using phpjs

使用phpjs

function parse_str(str, array) {
  //       discuss at: http://phpjs.org/functions/parse_str/
  //      original by: Cagri Ekin
  //      improved by: Michael White (http://getsprink.com)
  //      improved by: Jack
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: Onno Marsman
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: stag019
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
  // reimplemented by: stag019
  //         input by: Dreamer
  //         input by: Zaide (http://zaidesthings.com/)
  //         input by: David Pesta (http://davidpesta.com/)
  //         input by: jeicquest
  //             note: When no argument is specified, will put variables in global scope.
  //             note: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
  //             test: skip
  //        example 1: var arr = {};
  //        example 1: parse_str('first=foo&second=bar', arr);
  //        example 1: $result = arr
  //        returns 1: { first: 'foo', second: 'bar' }
  //        example 2: var arr = {};
  //        example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
  //        example 2: $result = arr
  //        returns 2: { str_a: "Jack and Jill didn't see the well." }
  //        example 3: var abc = {3:'a'};
  //        example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
  //        returns 3: {"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}

  var strArr = String(str)
    .replace(/^&/, '')
    .replace(/&$/, '')
    .split('&'),
    sal = strArr.length,
    i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
    postLeftBracketPos, keys, keysLen,
    fixStr = function(str) {
      return decodeURIComponent(str.replace(/\+/g, '%20'));
    };

  if (!array) {
    array = this.window;
  }

  for (i = 0; i < sal; i++) {
    tmp = strArr[i].split('=');
    key = fixStr(tmp[0]);
    value = (tmp.length < 2) ? '' : fixStr(tmp[1]);

    while (key.charAt(0) === ' ') {
      key = key.slice(1);
    }
    if (key.indexOf('\x00') > -1) {
      key = key.slice(0, key.indexOf('\x00'));
    }
    if (key && key.charAt(0) !== '[') {
      keys = [];
      postLeftBracketPos = 0;
      for (j = 0; j < key.length; j++) {
        if (key.charAt(j) === '[' && !postLeftBracketPos) {
          postLeftBracketPos = j + 1;
        } else if (key.charAt(j) === ']') {
          if (postLeftBracketPos) {
            if (!keys.length) {
              keys.push(key.slice(0, postLeftBracketPos - 1));
            }
            keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
            postLeftBracketPos = 0;
            if (key.charAt(j + 1) !== '[') {
              break;
            }
          }
        }
      }
      if (!keys.length) {
        keys = [key];
      }
      for (j = 0; j < keys[0].length; j++) {
        chr = keys[0].charAt(j);
        if (chr === ' ' || chr === '.' || chr === '[') {
          keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
        }
        if (chr === '[') {
          break;
        }
      }

      obj = array;
      for (j = 0, keysLen = keys.length; j < keysLen; j++) {
        key = keys[j].replace(/^['"]/, '')
          .replace(/['"]$/, '');
        lastIter = j !== keys.length - 1;
        lastObj = obj;
        if ((key !== '' && key !== ' ') || j === 0) {
          if (obj[key] === undef) {
            obj[key] = {};
          }
          obj = obj[key];
        } else { // To insert new dimension
          ct = -1;
          for (p in obj) {
            if (obj.hasOwnProperty(p)) {
              if (+p > ct && p.match(/^\d+$/g)) {
                ct = +p;
              }
            }
          }
          key = ct + 1;
        }
      }
      lastObj[key] = value;
    }
  }
}

#15


0  

FIRST U NEED TO DEFINE WHAT'S A GET VAR:

首先,你需要定义什么是得到VAR:

function getVar()
{
    this.length = 0;
    this.keys = [];
    this.push = function(key, value)
    {
        if(key=="") key = this.length++;
        this[key] = value;
        this.keys.push(key);
        return this[key];
    }
}

Than just read:

不仅仅是读:

function urlElement()
{
    var thisPrototype = window.location;
    for(var prototypeI in thisPrototype) this[prototypeI] = thisPrototype[prototypeI];
    this.Variables = new getVar();
    if(!this.search) return this;
    var variables = this.search.replace(/\?/g,'').split('&');
    for(var varI=0; varI<variables.length; varI++)
    {
        var nameval = variables[varI].split('=');
        var name = nameval[0].replace(/\]/g,'').split('[');
        var pVariable = this.Variables;
        for(var nameI=0;nameI<name.length;nameI++)
        {
            if(name.length-1==nameI) pVariable.push(name[nameI],nameval[1]);
            else var pVariable = (typeof pVariable[name[nameI]] != 'object')? pVariable.push(name[nameI],new getVar()) : pVariable[name[nameI]];
        }
    }
}

and use like:

和使用:

var mlocation = new urlElement();
mlocation = mlocation.Variables;
for(var key=0;key<mlocation.keys.length;key++)
{
    console.log(key);
    console.log(mlocation[mlocation.keys[key]];
}

#16


0  

This seems to be the best solution as it takes multiple parameters of the same name into consideration.

这似乎是最好的解决方案,因为它需要考虑相同名称的多个参数。

    function paramsToJSON(str) {
        var pairs = str.split('&');
        var result = {};
        pairs.forEach(function(pair) {
            pair = pair.split('=');
            var name = pair[0]
            var value = pair[1]
            if( name.length )
                if (result[name] !== undefined) {
                    if (!result[name].push) {
                        result[name] = [result[name]];
                    }
                    result[name].push(value || '');
                } else {
                    result[name] = value || '';
                }
        });
        return( result );
    }

<a href="index.html?x=1&x=2&x=3&y=blah">something</a>
paramsToJSON("x=1&x=2&x=3&y=blah"); 

console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON

I later decided to convert it to a jQuery plugin too...

后来我决定把它转换成jQuery插件……

$.fn.serializeURLParams = function() {
    var result = {};

    if( !this.is("a") || this.attr("href").indexOf("?") == -1 ) 
        return( result );

    var pairs = this.attr("href").split("?")[1].split('&');
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        var name = decodeURI(pair[0])
        var value = decodeURI(pair[1])
        if( name.length )
            if (result[name] !== undefined) {
                if (!result[name].push) {
                    result[name] = [result[name]];
                }
                result[name].push(value || '');
            } else {
                result[name] = value || '';
            }
    });
    return( result )
}

<a href="index.html?x=1&x=2&x=3&y=blah">something</a>
$("a").serializeURLParams(); 

console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON

Now, the first will accept the parameters only but the jQuery plugin will take the whole url and return the serialized parameters.

现在,第一个将只接受参数,但是jQuery插件将获取整个url并返回序列化的参数。

#17


0  

I needed to also deal with + in the query part of the URL (decodeURIComponent doesn't), so I adapted Wolfgang's code to become:

我还需要在URL的查询部分(decodeURIComponent)中处理+,所以我修改了沃尔夫冈的代码:

var search = location.search.substring(1);
search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)}):{};

In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.:

在我的例子中,我使用jQuery来获得URL就绪的表单参数,然后用这个技巧来构建一个对象,然后我可以轻松地更新对象上的参数,并重建查询URL,例如:

var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)});
objForm.anyParam += stringToAddToTheParam;
var serializedForm = $.param(objForm);

#18


0  

Building on top of Mike Causer's answer I've made this function which takes into consideration multiple params with the same key (foo=bar&foo=baz) and also comma-separated parameters (foo=bar,baz,bin). It also lets you search for a certain query key.

在Mike Causer的答案之上,我已经创建了这个函数,它考虑了具有相同键(foo=bar&foo=baz)和逗号分隔参数(foo=bar,baz,bin)的多个params。它还允许您搜索某个查询键。

function getQueryParams(queryKey) {
    var queryString = window.location.search;
    var query = {};
    var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        var key = decodeURIComponent(pair[0]);
        var value = decodeURIComponent(pair[1] || '');
        // Se possui uma vírgula no valor, converter em um array
        value = (value.indexOf(',') === -1 ? value : value.split(','));

        // Se a key já existe, tratar ela como um array
        if (query[key]) {
            if (query[key].constructor === Array) {
                // Array.concat() faz merge se o valor inserido for um array
                query[key] = query[key].concat(value);
            } else {
                // Se não for um array, criar um array contendo o valor anterior e o novo valor
                query[key] = [query[key], value];
            }
        } else {
            query[key] = value;
        }
    }

    if (typeof queryKey === 'undefined') {
        return query;
    } else {
        return query[queryKey];
    }
}

Example input: foo.html?foo=bar&foo=baz&foo=bez,boz,buz&bar=1,2,3

示例输入:foo.html ? foo = bar&foo = baz&foo =鹿角的第二叉,博兹,buz&bar = 1,2,3

Example output

示例输出

{
    foo: ["bar","baz","bez","boz","buz"],
    bar: ["1","2","3"]
}

#19


0  

The proposed solutions I found so far do not cover more complex scenarios.

到目前为止,我发现的解决方案没有涵盖更复杂的场景。

I needed to convert a query string like

我需要转换一个查询字符串,比如。

https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name

https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name

into an object like:

为一个对象:

{
    "Target": "Offer",
    "Method": "findAll",
    "fields": [
        "id",
        "name",
        "default_goal_name"
    ],
    "filters": {
        "has_goals_enabled": {
            "TRUE": "1"
        },
        "status": "active"
    }
}

OR:

或者:

https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999

https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999

INTO:

成:

{
    "Target": "Report",
    "Method": "getStats",
    "fields": [
        "Offer.name",
        "Advertiser.company",
        "Stat.clicks",
        "Stat.conversions",
        "Stat.cpa",
        "Stat.payout",
        "Stat.date",
        "Stat.offer_id",
        "Affiliate.company"
    ],
    "groups": [
        "Stat.offer_id",
        "Stat.date"
    ],
    "limit": "9999",
    "filters": {
        "Stat.affiliate_id": {
            "conditional": "EQUAL_TO",
            "values": "1831"
        }
    }
}

I compiled and adapted multiple solutions into one that actually works:

CODE:

代码:

var getParamsAsObject = function (query) {

    query = query.substring(query.indexOf('?') + 1);

    var re = /([^&=]+)=?([^&]*)/g;
    var decodeRE = /\+/g;

    var decode = function (str) {
        return decodeURIComponent(str.replace(decodeRE, " "));
    };

    var params = {}, e;
    while (e = re.exec(query)) {
        var k = decode(e[1]), v = decode(e[2]);
        if (k.substring(k.length - 2) === '[]') {
            k = k.substring(0, k.length - 2);
            (params[k] || (params[k] = [])).push(v);
        }
        else params[k] = v;
    }

    var assign = function (obj, keyPath, value) {
        var lastKeyIndex = keyPath.length - 1;
        for (var i = 0; i < lastKeyIndex; ++i) {
            var key = keyPath[i];
            if (!(key in obj))
                obj[key] = {}
            obj = obj[key];
        }
        obj[keyPath[lastKeyIndex]] = value;
    }

    for (var prop in params) {
        var structure = prop.split('[');
        if (structure.length > 1) {
            var levels = [];
            structure.forEach(function (item, i) {
                var key = item.replace(/[?[\]\\ ]/g, '');
                levels.push(key);
            });
            assign(params, levels, params[prop]);
            delete(params[prop]);
        }
    }
    return params;
};

#20


0  

ES6 one liner. Clean and simple.

ES6班轮。干净和简单。

var obj = Array.from(new URLSearchParams(location.search).keys()).reduce((sum, value,index,arr)=>{ return Object.assign({[value]: new URLSearchParams(location.search).get(value)}, sum); }, {});

#1


209  

Edit

This edit improves and explains the answer based on the comments.

这个编辑改进并根据评论解释了答案。

var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

Example

例子

Parse abc=foo&def=%5Basf%5D&xyz=5 in five steps:

在五个步骤中,解析abc=foo&def=%5Basf%5D&xyz=5:

  • decodeURI: abc=foo&def=[asf]&xyz=5
  • decodeURI:abc = foo&def = xyz(asf)= 5
  • Escape quotes: same, as there are no quotes
  • 转义引号:相同,因为没有引号。
  • Replace &: abc=foo","def=[asf]","xyz=5
  • 取代&:abc = foo”、“def =(asf)”、“xyz = 5
  • Replace =: abc":"foo","def":"[asf]","xyz":"5
  • 取代=:abc”:“foo”、“def”:“(asf)”、“xyz”:“5
  • Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}
  • Suround卷曲和引用:{“abc”:“foo”、“def”:“(asf)”,“xyz”:“5”}

which is legal JSON.

这是合法的JSON。

An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:

改进的解决方案允许搜索字符串中的更多字符。它使用了一个修订函数URI解码:

var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

Example

例子

search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";

gives

给了

Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}

Original answer

A one-liner:

一行程序:

JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')

#2


21  

Split on & to get name/value pairs, then split each pair on =. Here's an example:

分开并获取名称/值对,然后将每一对分开。这里有一个例子:

var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
var obj = str.split("&").reduce(function(prev, curr, i, arr) {
    var p = curr.split("=");
    prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
    return prev;
}, {});

Another approach, using regular expressions:

另一种方法,使用正则表达式:

var obj = {}; 
str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
    obj[decodeURIComponent(key)] = decodeURIComponent(value);
}); 

This is adapted from John Resig's "Search and Don’t Replace".

这是改编自John Resig的“搜索和不要替换”。

#3


11  

This is the simple version, obviously you'll want to add some error checking:

这是一个简单的版本,显然你需要添加一些错误检查:

var obj = {};
var pairs = queryString.split('&');
for(i in pairs){
    var split = pairs[i].split('=');
    obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}

#4


9  

I found $.String.deparam the most complete pre built solution (can do nested objects etc.). Check out the documentation.

我发现$. string .deparam是最完整的预构建解决方案(可以做嵌套对象等)。查看文档。

#5


6  

I had the same problem, tried the solutions here, but none of them really worked, since I had arrays in the URL parameters, like this:

我有同样的问题,尝试过这里的解决方案,但是没有一个真正起作用,因为我在URL参数中有数组,像这样:

?param[]=5&param[]=8&othr_param=abc&param[]=string

So I ended up writing my own JS function, which makes an array out of the param in URI:

所以我最后写了我自己的JS函数,它在URI中创建了一个数组

/**
 * Creates an object from URL encoded data
 */
var createObjFromURI = function() {
    var uri = decodeURI(location.search.substr(1));
    var chunks = uri.split('&');
    var params = Object();

    for (var i=0; i < chunks.length ; i++) {
        var chunk = chunks[i].split('=');
        if(chunk[0].search("\\[\\]") !== -1) {
            if( typeof params[chunk[0]] === 'undefined' ) {
                params[chunk[0]] = [chunk[1]];

            } else {
                params[chunk[0]].push(chunk[1]);
            }


        } else {
            params[chunk[0]] = chunk[1];
        }
    }

    return params;
}

#6


5  

Another solution based on the latest standard of URLSearchParams (https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

基于URLSearchParams最新标准的另一种解决方案(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

function getQueryParamsObject() {
  const searchParams = new URLSearchParams(location.search.slice(1));
  return searchParams
    ? _.fromPairs(Array.from(searchParams.entries()))
    : {};
}

Please note that this solution is making use of

请注意这个解决方案正在使用。

Array.from (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

Array.from(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

and _.fromPairs (https://lodash.com/docs#fromPairs) of lodash for the sake of simplicity.

并且为了简单起见,从lodash对(https://lodash.com/docs# from成对)进行。

It should be easy to create a more compatible solution since you have access to searchParams.entries() iterator.

创建一个更兼容的解决方案应该很容易,因为您可以访问searchParams.entries()迭代器。

#7


3  

Using ES6, URL API and URLSearchParams API.

使用ES6, URL API和URLSearchParams API。

function objectifyQueryString(url) {
  let _url = new URL(url);
  let _params = new URLSearchParams(_url.search);
  let query = Array.from(_params.keys()).reduce((sum, value)=>{
    return Object.assign({[value]: _params.get(value)}, sum);
  }, {});
  return query;
}

#8


2  

There is no native solution that I'm aware of. Dojo has a built-in unserialization method if you use that framework by chance.

我没有意识到本地的解决方案。如果使用这个框架,Dojo有一个内置的非序列化方法。

Otherwise you can implement it yourself rather simply:

否则,你自己就可以简单地实现它:

function unserialize(str) {
  str = decodeURIComponent(str);
  var chunks = str.split('&'),
      obj = {};
  for(var c=0; c < chunks.length; c++) {
    var split = chunks[c].split('=', 2);
    obj[split[0]] = split[1];
  }
  return obj;
}

edit: added decodeURIComponent()

编辑:添加decodeURIComponent()

#9


2  

There's a lightweight library called YouAreI.js that's tested and makes this really easy.

有一个轻量级的库叫做YouAreI。这是经过测试的,这真的很简单。

YouAreI = require('YouAreI')
uri = new YouAreI('http://user:pass@www.example.com:3000/a/b/c?d=dad&e=1&f=12.3#fragment');

uri.query_get() => { d: 'dad', e: '1', f: '12.3' }

#10


2  

A concise solution:

一个简洁的解决方案:

location.search
  .slice(1)
  .split('&')
  .map(p => p.split('='))
  .reduce((obj, pair) => {
    const [key, value] = pair.map(decodeURIComponent);
    return ({ ...obj, [key]: value })
  }, {});

#11


1  

Here's one I use:

这是一个我使用:

var params = {};
window.location.search.substring(1).split('&').forEach(function(pair) {
  pair = pair.split('=');
  if (pair[1] !== undefined) {
    var key = decodeURIComponent(pair[0]),
        val = decodeURIComponent(pair[1]),
        val = val ? val.replace(/\++/g,' ').trim() : '';

    if (key.length === 0) {
      return;
    }
    if (params[key] === undefined) {
      params[key] = val;
    }
    else {
      if ("function" !== typeof params[key].push) {
        params[key] = [params[key]];
      }
      params[key].push(val);
    }
  }
});
console.log(params);

Basic usage, eg.
?a=aa&b=bb
Object {a: "aa", b: "bb"}

基本用法,例如。a:“aa”,b:“bb”

Duplicate params, eg.
?a=aa&b=bb&c=cc&c=potato
Object {a: "aa", b: "bb", c: ["cc","potato"]}

重复的参数,例如。? = aa&b = bb&c = cc&c =土豆对象{“aa”,b:“bb”,c:[“cc”、“土豆”]}

Missing keys, eg.
?a=aa&b=bb&=cc
Object {a: "aa", b: "bb"}

丢失的钥匙,如。a: "aa", b: "bb"}

Missing values, eg.
?a=aa&b=bb&c
Object {a: "aa", b: "bb"}

缺失值,例如。a: "aa", b: "bb"}

The above JSON/regex solutions throw a syntax error on this wacky url:
?a=aa&b=bb&c=&=dd&e
Object {a: "aa", b: "bb", c: ""}

上面的JSON/regex解决方案在这个古怪的url上抛出一个语法错误:?a=aa&b=bb&c=&=dd&e对象{a:“aa”,b:“bb”,c:“}”

#12


1  

Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc):

这是我的快速和不干净的版本,主要是将“&”分隔的URL参数分解为数组元素,然后遍历该数组,并将“=”分隔的键/值对添加到一个对象中。我使用decodeURIComponent()将已编码的字符转换为它们的普通字符串等效项(因此%20变成一个空格,%26变成'&'等):

function deparam(paramStr) {
    let paramArr = paramStr.split('&');     
    let paramObj = {};
    paramArr.forEach(e=>{
        let param = e.split('=');
        paramObj[param[0]] = decodeURIComponent(param[1]);
    });
    return paramObj;
}

example:

例子:

deparam('abc=foo&def=%5Basf%5D&xyz=5')

returns

返回

{
    abc: "foo"
    def:"[asf]"
    xyz :"5"
}

The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.

唯一的问题是xyz是一个字符串,而不是一个数字(由于使用了decodeURIComponent()),但除此之外,它还不是一个不好的起点。

#13


1  

//under ES6 
const getUrlParamAsObject = (url = window.location.href) => {
    let searchParams = url.split('?')[1];
    const result = {};
    //in case the queryString is empty
    if (searchParams!==undefined) {
        const paramParts = searchParams.split('&');
        for(let part of paramParts) {
            let paramValuePair = part.split('=');
            //exclude the case when the param has no value
            if(paramValuePair.length===2) {
                result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
            }
        }

    }
    return result;
}

#14


1  

Using phpjs

使用phpjs

function parse_str(str, array) {
  //       discuss at: http://phpjs.org/functions/parse_str/
  //      original by: Cagri Ekin
  //      improved by: Michael White (http://getsprink.com)
  //      improved by: Jack
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: Onno Marsman
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: stag019
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
  // reimplemented by: stag019
  //         input by: Dreamer
  //         input by: Zaide (http://zaidesthings.com/)
  //         input by: David Pesta (http://davidpesta.com/)
  //         input by: jeicquest
  //             note: When no argument is specified, will put variables in global scope.
  //             note: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
  //             test: skip
  //        example 1: var arr = {};
  //        example 1: parse_str('first=foo&second=bar', arr);
  //        example 1: $result = arr
  //        returns 1: { first: 'foo', second: 'bar' }
  //        example 2: var arr = {};
  //        example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
  //        example 2: $result = arr
  //        returns 2: { str_a: "Jack and Jill didn't see the well." }
  //        example 3: var abc = {3:'a'};
  //        example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
  //        returns 3: {"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}

  var strArr = String(str)
    .replace(/^&/, '')
    .replace(/&$/, '')
    .split('&'),
    sal = strArr.length,
    i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
    postLeftBracketPos, keys, keysLen,
    fixStr = function(str) {
      return decodeURIComponent(str.replace(/\+/g, '%20'));
    };

  if (!array) {
    array = this.window;
  }

  for (i = 0; i < sal; i++) {
    tmp = strArr[i].split('=');
    key = fixStr(tmp[0]);
    value = (tmp.length < 2) ? '' : fixStr(tmp[1]);

    while (key.charAt(0) === ' ') {
      key = key.slice(1);
    }
    if (key.indexOf('\x00') > -1) {
      key = key.slice(0, key.indexOf('\x00'));
    }
    if (key && key.charAt(0) !== '[') {
      keys = [];
      postLeftBracketPos = 0;
      for (j = 0; j < key.length; j++) {
        if (key.charAt(j) === '[' && !postLeftBracketPos) {
          postLeftBracketPos = j + 1;
        } else if (key.charAt(j) === ']') {
          if (postLeftBracketPos) {
            if (!keys.length) {
              keys.push(key.slice(0, postLeftBracketPos - 1));
            }
            keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
            postLeftBracketPos = 0;
            if (key.charAt(j + 1) !== '[') {
              break;
            }
          }
        }
      }
      if (!keys.length) {
        keys = [key];
      }
      for (j = 0; j < keys[0].length; j++) {
        chr = keys[0].charAt(j);
        if (chr === ' ' || chr === '.' || chr === '[') {
          keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
        }
        if (chr === '[') {
          break;
        }
      }

      obj = array;
      for (j = 0, keysLen = keys.length; j < keysLen; j++) {
        key = keys[j].replace(/^['"]/, '')
          .replace(/['"]$/, '');
        lastIter = j !== keys.length - 1;
        lastObj = obj;
        if ((key !== '' && key !== ' ') || j === 0) {
          if (obj[key] === undef) {
            obj[key] = {};
          }
          obj = obj[key];
        } else { // To insert new dimension
          ct = -1;
          for (p in obj) {
            if (obj.hasOwnProperty(p)) {
              if (+p > ct && p.match(/^\d+$/g)) {
                ct = +p;
              }
            }
          }
          key = ct + 1;
        }
      }
      lastObj[key] = value;
    }
  }
}

#15


0  

FIRST U NEED TO DEFINE WHAT'S A GET VAR:

首先,你需要定义什么是得到VAR:

function getVar()
{
    this.length = 0;
    this.keys = [];
    this.push = function(key, value)
    {
        if(key=="") key = this.length++;
        this[key] = value;
        this.keys.push(key);
        return this[key];
    }
}

Than just read:

不仅仅是读:

function urlElement()
{
    var thisPrototype = window.location;
    for(var prototypeI in thisPrototype) this[prototypeI] = thisPrototype[prototypeI];
    this.Variables = new getVar();
    if(!this.search) return this;
    var variables = this.search.replace(/\?/g,'').split('&');
    for(var varI=0; varI<variables.length; varI++)
    {
        var nameval = variables[varI].split('=');
        var name = nameval[0].replace(/\]/g,'').split('[');
        var pVariable = this.Variables;
        for(var nameI=0;nameI<name.length;nameI++)
        {
            if(name.length-1==nameI) pVariable.push(name[nameI],nameval[1]);
            else var pVariable = (typeof pVariable[name[nameI]] != 'object')? pVariable.push(name[nameI],new getVar()) : pVariable[name[nameI]];
        }
    }
}

and use like:

和使用:

var mlocation = new urlElement();
mlocation = mlocation.Variables;
for(var key=0;key<mlocation.keys.length;key++)
{
    console.log(key);
    console.log(mlocation[mlocation.keys[key]];
}

#16


0  

This seems to be the best solution as it takes multiple parameters of the same name into consideration.

这似乎是最好的解决方案,因为它需要考虑相同名称的多个参数。

    function paramsToJSON(str) {
        var pairs = str.split('&');
        var result = {};
        pairs.forEach(function(pair) {
            pair = pair.split('=');
            var name = pair[0]
            var value = pair[1]
            if( name.length )
                if (result[name] !== undefined) {
                    if (!result[name].push) {
                        result[name] = [result[name]];
                    }
                    result[name].push(value || '');
                } else {
                    result[name] = value || '';
                }
        });
        return( result );
    }

<a href="index.html?x=1&x=2&x=3&y=blah">something</a>
paramsToJSON("x=1&x=2&x=3&y=blah"); 

console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON

I later decided to convert it to a jQuery plugin too...

后来我决定把它转换成jQuery插件……

$.fn.serializeURLParams = function() {
    var result = {};

    if( !this.is("a") || this.attr("href").indexOf("?") == -1 ) 
        return( result );

    var pairs = this.attr("href").split("?")[1].split('&');
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        var name = decodeURI(pair[0])
        var value = decodeURI(pair[1])
        if( name.length )
            if (result[name] !== undefined) {
                if (!result[name].push) {
                    result[name] = [result[name]];
                }
                result[name].push(value || '');
            } else {
                result[name] = value || '';
            }
    });
    return( result )
}

<a href="index.html?x=1&x=2&x=3&y=blah">something</a>
$("a").serializeURLParams(); 

console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON

Now, the first will accept the parameters only but the jQuery plugin will take the whole url and return the serialized parameters.

现在,第一个将只接受参数,但是jQuery插件将获取整个url并返回序列化的参数。

#17


0  

I needed to also deal with + in the query part of the URL (decodeURIComponent doesn't), so I adapted Wolfgang's code to become:

我还需要在URL的查询部分(decodeURIComponent)中处理+,所以我修改了沃尔夫冈的代码:

var search = location.search.substring(1);
search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)}):{};

In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.:

在我的例子中,我使用jQuery来获得URL就绪的表单参数,然后用这个技巧来构建一个对象,然后我可以轻松地更新对象上的参数,并重建查询URL,例如:

var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)});
objForm.anyParam += stringToAddToTheParam;
var serializedForm = $.param(objForm);

#18


0  

Building on top of Mike Causer's answer I've made this function which takes into consideration multiple params with the same key (foo=bar&foo=baz) and also comma-separated parameters (foo=bar,baz,bin). It also lets you search for a certain query key.

在Mike Causer的答案之上,我已经创建了这个函数,它考虑了具有相同键(foo=bar&foo=baz)和逗号分隔参数(foo=bar,baz,bin)的多个params。它还允许您搜索某个查询键。

function getQueryParams(queryKey) {
    var queryString = window.location.search;
    var query = {};
    var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        var key = decodeURIComponent(pair[0]);
        var value = decodeURIComponent(pair[1] || '');
        // Se possui uma vírgula no valor, converter em um array
        value = (value.indexOf(',') === -1 ? value : value.split(','));

        // Se a key já existe, tratar ela como um array
        if (query[key]) {
            if (query[key].constructor === Array) {
                // Array.concat() faz merge se o valor inserido for um array
                query[key] = query[key].concat(value);
            } else {
                // Se não for um array, criar um array contendo o valor anterior e o novo valor
                query[key] = [query[key], value];
            }
        } else {
            query[key] = value;
        }
    }

    if (typeof queryKey === 'undefined') {
        return query;
    } else {
        return query[queryKey];
    }
}

Example input: foo.html?foo=bar&foo=baz&foo=bez,boz,buz&bar=1,2,3

示例输入:foo.html ? foo = bar&foo = baz&foo =鹿角的第二叉,博兹,buz&bar = 1,2,3

Example output

示例输出

{
    foo: ["bar","baz","bez","boz","buz"],
    bar: ["1","2","3"]
}

#19


0  

The proposed solutions I found so far do not cover more complex scenarios.

到目前为止,我发现的解决方案没有涵盖更复杂的场景。

I needed to convert a query string like

我需要转换一个查询字符串,比如。

https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name

https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name

into an object like:

为一个对象:

{
    "Target": "Offer",
    "Method": "findAll",
    "fields": [
        "id",
        "name",
        "default_goal_name"
    ],
    "filters": {
        "has_goals_enabled": {
            "TRUE": "1"
        },
        "status": "active"
    }
}

OR:

或者:

https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999

https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999

INTO:

成:

{
    "Target": "Report",
    "Method": "getStats",
    "fields": [
        "Offer.name",
        "Advertiser.company",
        "Stat.clicks",
        "Stat.conversions",
        "Stat.cpa",
        "Stat.payout",
        "Stat.date",
        "Stat.offer_id",
        "Affiliate.company"
    ],
    "groups": [
        "Stat.offer_id",
        "Stat.date"
    ],
    "limit": "9999",
    "filters": {
        "Stat.affiliate_id": {
            "conditional": "EQUAL_TO",
            "values": "1831"
        }
    }
}

I compiled and adapted multiple solutions into one that actually works:

CODE:

代码:

var getParamsAsObject = function (query) {

    query = query.substring(query.indexOf('?') + 1);

    var re = /([^&=]+)=?([^&]*)/g;
    var decodeRE = /\+/g;

    var decode = function (str) {
        return decodeURIComponent(str.replace(decodeRE, " "));
    };

    var params = {}, e;
    while (e = re.exec(query)) {
        var k = decode(e[1]), v = decode(e[2]);
        if (k.substring(k.length - 2) === '[]') {
            k = k.substring(0, k.length - 2);
            (params[k] || (params[k] = [])).push(v);
        }
        else params[k] = v;
    }

    var assign = function (obj, keyPath, value) {
        var lastKeyIndex = keyPath.length - 1;
        for (var i = 0; i < lastKeyIndex; ++i) {
            var key = keyPath[i];
            if (!(key in obj))
                obj[key] = {}
            obj = obj[key];
        }
        obj[keyPath[lastKeyIndex]] = value;
    }

    for (var prop in params) {
        var structure = prop.split('[');
        if (structure.length > 1) {
            var levels = [];
            structure.forEach(function (item, i) {
                var key = item.replace(/[?[\]\\ ]/g, '');
                levels.push(key);
            });
            assign(params, levels, params[prop]);
            delete(params[prop]);
        }
    }
    return params;
};

#20


0  

ES6 one liner. Clean and simple.

ES6班轮。干净和简单。

var obj = Array.from(new URLSearchParams(location.search).keys()).reduce((sum, value,index,arr)=>{ return Object.assign({[value]: new URLSearchParams(location.search).get(value)}, sum); }, {});