【问题标题】:Decode JSON, including array from URL paramter in JavaScript解码 JSON,包括 JavaScript 中 URL 参数的数组
【发布时间】:2020-05-31 01:24:10
【问题描述】:

我有这个网址:

http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000

现在我正在尝试将 URL 编码为对象。这是我目前的尝试:

function URLToArray(url) {
  var request = {};
  var pairs = url.substring(url.indexOf('?') + 1).split('&');
  for (var i = 0; i < pairs.length; i++) {
      if(!pairs[i])
          continue;
      var pair = pairs[i].split('=');
      request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
   }
   return request;
}

但是我需要这个函数将数组作为 JSON 数组返回,而不是它目前的方式:

如何让我的函数返回我的对象​​数组?

【问题讨论】:

标签: javascript json object url get


【解决方案1】:

你可以先用help from this question获取对象。

使用带有正则表达式循环的URLSearchParams 的示例:

const url = "http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000";

const regex = /^([a-z0-9]+)?\[([a-zA-Z0-9]+)\]*/mi;

function URLToArray(url) {
	url = decodeURIComponent(url);
  const args = new URLSearchParams(url.split('?')[1]);
  
  let request = {};
  args.forEach((value, key) => {
  	let baseKey = key;
    let ogValue = value;
    let lastKey = '';
  	while ((m = regex.exec(key)) !== null) {
    	if (m[1]) {
      	baseKey = m[1];
        value = request[baseKey] || {};
      	request[baseKey] = value;
      }
      
      if (m[2]) {
      	value = value[lastKey] || value;
        value[m[2]] = value[m[2]] || {};
      	lastKey = m[2];
      }
      
      key = key.replace(m[0], '');
    }
    
    if (lastKey) {
    	value[lastKey] = ogValue;
    } else {
    	request[baseKey] = value;
    }
  });
  return request;
}

console.log(URLToArray(url));

这并不完美,您将留下嵌套对象,而不是适合您的 items 的数组,并且可能有一些库可以更好地实现相同的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多