Query-string encoding of a Javascript Object

前端 未结 30 2962
渐次进展
渐次进展 2020-11-22 00:23

Do you know a fast and simple way to encode a Javascript Object into a string that I can pass via a GET Request?

No jQuery, no

相关标签:
30条回答
  • 2020-11-22 01:03

    This is a solution that will work for .NET backends out of the box. I have taken the primary answer of this thread and updated it to fit our .NET needs.

    function objectToQuerystring(params) {
    var result = '';
    
        function convertJsonToQueryString(data, progress, name) {
            name = name || '';
            progress = progress || '';
            if (typeof data === 'object') {
                Object.keys(data).forEach(function (key) {
                    var value = data[key];
                    if (name == '') {
                        convertJsonToQueryString(value, progress, key);
                    } else {
                        if (isNaN(parseInt(key))) {
                            convertJsonToQueryString(value, progress, name + '.' + key);
                        } else {
                            convertJsonToQueryString(value, progress, name + '[' + key+ ']');
                        }
                    }
                })
            } else {
                result = result ? result.concat('&') : result.concat('?');
                result = result.concat(`${name}=${data}`);
            }
        }
    
        convertJsonToQueryString(params);
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 01:05

    like this?

    serialize = function(obj) {
      var str = [];
      for (var p in obj)
        if (obj.hasOwnProperty(p)) {
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
      return str.join("&");
    }
    
    console.log(serialize({
      foo: "hi there",
      bar: "100%"
    }));
    // foo=hi%20there&bar=100%25

    Edit: this one also converts recursive objects (using php "array" notation for the query string)

    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

    0 讨论(0)
  • 2020-11-22 01:06

    Here's the coffeescript version of accepted answer. This might save time to someone.

    serialize = (obj, prefix) ->
      str = []
      for p, v of obj
        k = if prefix then prefix + "[" + p + "]" else p
        if typeof v == "object"
          str.push(serialize(v, k))
        else
          str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v))
    
      str.join("&")
    
    0 讨论(0)
  • 2020-11-22 01:09

    use JSON.

    take a look at this question for ideas on how to implement.

    0 讨论(0)
  • 2020-11-22 01:09

    This one skips null/undefined values

    export function urlEncodeQueryParams(data) {
        const params = Object.keys(data).map(key => data[key] ? `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}` : '');
        return params.filter(value => !!value).join('&');
    }
    
    0 讨论(0)
  • 2020-11-22 01:10

    ES6 SOLUTION FOR QUERY STRING ENCODING OF A JAVASCRIPT OBJECT

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