是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?

没有jQuery,没有其他框架-只有纯JavaScript:)


当前回答

ES6解决方案用于JavaScript对象的查询字符串编码

const params = {
  a: 1,
  b: 'query stringify',
  c: null,
  d: undefined,
  f: '',
  g: { foo: 1, bar: 2 },
  h: ['Winterfell', 'Westeros', 'Braavos'],
  i: { first: { second: { third: 3 }}}
}

static toQueryString(params = {}, prefix) {
  const query = Object.keys(params).map((k) => {
    let key = k;
    const value = params[key];

    if (!value && (value === null || value === undefined || isNaN(value))) {
      value = '';
    }

    switch (params.constructor) {
      case Array:
        key = `${prefix}[]`;
        break;
      case Object:
        key = (prefix ? `${prefix}[${key}]` : key);
        break;
    }

    if (typeof value === 'object') {
      return this.toQueryString(value, key); // for nested objects
    }

    return `${key}=${encodeURIComponent(value)}`;
  });

  return query.join('&');
}

toQueryString (params)

"a=1&b=query%20stringify&c=&d=&f=&g[foo]=1&g[bar]=2&h[]=Winterfell&h[]=Westeros&h[]=Braavos&i[first][second][third]=3"

其他回答

如果您需要发送任意对象,那么GET是一个坏主意,因为有限制的url长度,用户代理和web服务器将接受。我的建议是建立一个名称-值对数组来发送,然后建立一个查询字符串:

function QueryStringBuilder() {
    var nameValues = [];

    this.add = function(name, value) {
        nameValues.push( {name: name, value: value} );
    };

    this.toQueryString = function() {
        var segments = [], nameValue;
        for (var i = 0, len = nameValues.length; i < len; i++) {
            nameValue = nameValues[i];
            segments[i] = encodeURIComponent(nameValue.name) + "=" + encodeURIComponent(nameValue.value);
        }
        return segments.join("&");
    };
}

var qsb = new QueryStringBuilder();
qsb.add("veg", "cabbage");
qsb.add("vegCount", "5");

alert( qsb.toQueryString() );

我有一个更简单的解决方案,它不使用任何第三方库,并且已经易于在任何具有“Object”的浏览器中使用。键”(也就是所有现代浏览器+ edge + ie):

In ES5

function(a){
    if( typeof(a) !== 'object' ) 
        return '';
    return `?${Object.keys(a).map(k=>`${k}=${a[k]}`).join('&')}`;
}

在胡

function(a){
    if( typeof(a) !== 'object' ) 
        return '';
    return '?' + Object.keys(a).map(function(k){ return k + '=' + a[k] }).join('&');
}

是这样的:

Serialize =函数(obj) { Var STR = []; For (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))); } 返回str.join(“&”); } console.log(序列化({ Foo:“你好”, 栏:“100%” })); / / foo =你好% 20 there&bar 25 = 100%

它还转换递归对象(使用PHP“数组”符号表示查询字符串):

serialize = function(obj, prefix) { var str = [], p; for (p in obj) { if (obj.hasOwnProperty(p)) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push((v !== null && typeof v === "object") ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return str.join("&"); } console.log(serialize({ foo: "hi there", bar: { blah: 123, quux: [1, 2, 3] } })); // foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3

以更好的方式做这件事。

它可以处理标准查询形式的递归对象或数组,如a=val&b[0]=val&b[1]=val&c=val&d[some key]=val。这是最后一个函数。

逻辑、功能

const objectToQueryString = (initialObj) => {
  const reducer = (obj, parentPrefix = null) => (prev, key) => {
    const val = obj[key];
    key = encodeURIComponent(key);
    const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;

    if (val == null || typeof val === 'function') {
      prev.push(`${prefix}=`);
      return prev;
    }

    if (['number', 'boolean', 'string'].includes(typeof val)) {
      prev.push(`${prefix}=${encodeURIComponent(val)}`);
      return prev;
    }

    prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
    return prev;
  };

  return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};

例子

const testCase1 = {
  name: 'Full Name',
  age: 30
}

const testCase2 = {
  name: 'Full Name',
  age: 30,
  children: [
    {name: 'Child foo'},
    {name: 'Foo again'}
  ],
  wife: {
    name: 'Very Difficult to say here'
  }
}

console.log(objectToQueryString(testCase1));
console.log(objectToQueryString(testCase2));

现场测试

展开下面的代码片段,在浏览器中验证结果-

const objectToQueryString = (initialObj) => { const reducer = (obj, parentPrefix = null) => (prev, key) => { const val = obj[key]; key = encodeURIComponent(key); const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key; if (val == null || typeof val === 'function') { prev.push(`${prefix}=`); return prev; } if (['number', 'boolean', 'string'].includes(typeof val)) { prev.push(`${prefix}=${encodeURIComponent(val)}`); return prev; } prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&')); return prev; }; return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&'); }; const testCase1 = { name: 'Full Name', age: 30 } const testCase2 = { name: 'Full Name', age: 30, children: [ {name: 'Child foo'}, {name: 'Foo again'} ], wife: { name: 'Very Difficult to say here' } } console.log(objectToQueryString(testCase1)); console.log(objectToQueryString(testCase2));

需要考虑的事情。

它跳过函数、null和未定义的值 它跳过空对象和数组的键和值。 它不处理用new Number(1)或new String('my String ')创建的Number或String对象,因为没有人应该这样做

如果你想将整个对象作为一个参数传递,例如,?filter={param1: "val1", param2: "val2"}:

const serializeObject = (obj) => {
  let objStr = JSON.stringify(obj);

  objStr = objStr.replace(/\{/g, encodeURIComponent("{"));
  objStr = objStr.replace(/}/g, encodeURIComponent("}"));
  objStr = objStr.replace(/:/g, encodeURIComponent(":"));

  return objStr;
};

let res = serializeObject({param1: "val1", param2: "val2"});
console.log("serializeObject:", res); //%7B"param1"%3A"val1","param2"%3A"val2"%7D
console.log("serializeObject-decoded:", decodeURIComponent(res)); //{"param1":"val1","param2":"val2"}