Query-string encoding of a Javascript Object

前端 未结 30 2907
渐次进展
渐次进展 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 00:44

    Do you need to send arbitrary objects? If so, GET is a bad idea since there are limits to the lengths of URLs that user agents and web servers will accepts. My suggestion would be to build up an array of name-value pairs to send and then build up a query string:

    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() );
    
    0 讨论(0)
  • 2020-11-22 00:46

    You can also achieve this by using simple JavaScript.

    const stringData = '?name=Nikhil&surname=Mahirrao&age=30';
        
    const newData= {};
    stringData.replace('?', '').split('&').map((value) => {
      const temp = value.split('=');
      newData[temp[0]] = temp[1];
    });
    
    console.log('stringData: '+stringData);
    console.log('newData: ');
    console.log(newData);

    0 讨论(0)
  • 2020-11-22 00:47

    Here's a one liner in ES6:

    Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
    
    0 讨论(0)
  • 2020-11-22 00:49

    I suggest using the URLSearchParams interface:

    const searchParams = new URLSearchParams();
    const params = {foo: "hi there", bar: "100%" };
    Object.keys(params).forEach(key => searchParams.append(key, params[key]));
    console.log(searchParams.toString())

    Or by passing the search object into the constructor like this:

    const params = {foo: "hi there", bar: "100%" };
    const queryString = new URLSearchParams(params).toString();
    console.log(queryString);

    0 讨论(0)
  • 2020-11-22 00:49

    Just another way (no recursive object):

       getQueryString = function(obj)
       {
          result = "";
    
          for(param in obj)
             result += ( encodeURIComponent(param) + '=' + encodeURIComponent(obj[param]) + '&' );
    
          if(result) //it's not empty string when at least one key/value pair was added. In such case we need to remove the last '&' char
             result = result.substr(0, result.length - 1); //If length is zero or negative, substr returns an empty string [ref. http://msdn.microsoft.com/en-us/library/0esxc5wy(v=VS.85).aspx]
    
          return result;
       }
    
    alert( getQueryString({foo: "hi there", bar: 123, quux: 2 }) );
    
    0 讨论(0)
  • 2020-11-22 00:51

    I made a comparison of JSON stringifiers and the results are as follows:

    JSON:    {"_id":"5973782bdb9a930533b05cb2","isActive":true,"balance":"$1,446.35","age":32,"name":"Logan Keller","email":"logankeller@artiq.com","phone":"+1 (952) 533-2258","friends":[{"id":0,"name":"Colon Salazar"},{"id":1,"name":"French Mcneil"},{"id":2,"name":"Carol Martin"}],"favoriteFruit":"banana"}
    Rison:   (_id:'5973782bdb9a930533b05cb2',age:32,balance:'$1,446.35',email:'logankeller@artiq.com',favoriteFruit:banana,friends:!((id:0,name:'Colon Salazar'),(id:1,name:'French Mcneil'),(id:2,name:'Carol Martin')),isActive:!t,name:'Logan Keller',phone:'+1 (952) 533-2258')
    O-Rison: _id:'5973782bdb9a930533b05cb2',age:32,balance:'$1,446.35',email:'logankeller@artiq.com',favoriteFruit:banana,friends:!((id:0,name:'Colon Salazar'),(id:1,name:'French Mcneil'),(id:2,name:'Carol Martin')),isActive:!t,name:'Logan Keller',phone:'+1 (952) 533-2258'
    JSURL:   ~(_id~'5973782bdb9a930533b05cb2~isActive~true~balance~'!1*2c446.35~age~32~name~'Logan*20Keller~email~'logankeller*40artiq.com~phone~'*2b1*20*28952*29*20533-2258~friends~(~(id~0~name~'Colon*20Salazar)~(id~1~name~'French*20Mcneil)~(id~2~name~'Carol*20Martin))~favoriteFruit~'banana)
    QS:      _id=5973782bdb9a930533b05cb2&isActive=true&balance=$1,446.35&age=32&name=Logan Keller&email=logankeller@artiq.com&phone=+1 (952) 533-2258&friends[0][id]=0&friends[0][name]=Colon Salazar&friends[1][id]=1&friends[1][name]=French Mcneil&friends[2][id]=2&friends[2][name]=Carol Martin&favoriteFruit=banana
    URLON:   $_id=5973782bdb9a930533b05cb2&isActive:true&balance=$1,446.35&age:32&name=Logan%20Keller&email=logankeller@artiq.com&phone=+1%20(952)%20533-2258&friends@$id:0&name=Colon%20Salazar;&$id:1&name=French%20Mcneil;&$id:2&name=Carol%20Martin;;&favoriteFruit=banana
    QS-JSON: isActive=true&balance=%241%2C446.35&age=32&name=Logan+Keller&email=logankeller%40artiq.com&phone=%2B1+(952)+533-2258&friends(0).id=0&friends(0).name=Colon+Salazar&friends(1).id=1&friends(1).name=French+Mcneil&friends(2).id=2&friends(2).name=Carol+Martin&favoriteFruit=banana
    

    The shortest among them is URL Object Notation.

    0 讨论(0)
提交回复
热议问题