把Javascript 对象转换为键值对连接符字符串的方法总结

 

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 other frameworks - just plain Javascript :)

shareimprove this question
 
    
Why can't JQuery be a solution if there is an appropriate one for your solution? – eaglei22 Mar 30 '17 at 22:38
    
@eaglei22 because at the time I was working on a project for an IPTV set top box device and no external libraries were allowed. ;-) – Napolux Mar 31 '17 at 8:22
1  
Thanks for the response. I see this specification from time to time and always wondered a scenario why. Well, now I got one, thanks! :) – eaglei22 Mar 31 '17 at 13:48
4  
@eaglei22 Because sometimes you don't want to load a large library to get one element by id. – Aaron HarunJun 26 '17 at 20:46

 

 
up vote576down voteaccepted

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
shareimprove this answer
 
2  
Thanks a lot, that's the fast&clean solution I was looking for! – Napolux Nov 11 '09 at 12:43
8  
note p should be encodeURIComponent-ed too – bobince Nov 11 '09 at 12:43
2  
Won't it break given {foo: [1,2,3], bar: "100%" } ? – Quentin Nov 11 '09 at 12:53
1  
@Ofri: For POST requests to a server set up to receive it, JSON is a good choice. For GET requests, if you're sending anything other than a few simple parameters to the server then it's likely your design is wrong. – Tim Down Nov 11 '09 at 14:25
2  
@Marcel That's because the function doesn't check for hasOwnProperty. I've updated your fiddle so now it does: jsfiddle.net/rudiedirkx/U5Tyb/1 – Rudie Jan 5 '13 at 18:22

jQuery has a function for this, jQuery.param(), if you're already using it you can use that:http://api.jquery.com/jquery.param/

example:

var params = { width:1680, height:1050 };
var str = jQuery.param( params );

str now contains width=1680&height=1050

shareimprove this answer
 
78  
quoting Napolux (the OP): "just plain Javascript". :P – Sk8erPeter Jul 18 '12 at 15:53
67  
+1 This is still useful because I'm already using jQuery. – David Harkness Jul 31 '12 at 20:44
5  
jQuery.param() has sinister behavior. Try to execute var a = []; a[2564] = 12; console.log(jQuery.param({ propertylist: a })); to see what I mean. – akond Aug 14 '13 at 12:32
10  
@akond The jQuery documentation specifically says that you may not pass in a bare array. – Ariel Jun 26 '14 at 20:47
1  
@Ariel that line is only valid if the argument to param is an array. Passing in an object that contains an array does not invoke any of those rules. – Chris Hall Dec 11 '14 at 17:52 
Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')

Edit: I like this one-liner, but I bet it would be a more popular answer if it matched the accepted answer semantically:

function serialize( obj ) {
  return '?'+Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
}
shareimprove this answer
 
1  
nice. now, that's better. crisp and refreshing. – Todd Jan 7 '15 at 15:47
1  
A dedicated line for the reduct function would greatly improve the readability though. – Aurélien Ribon Apr 20 '15 at 14:48
37  
Using .map() instead of .reduce() would be even simpler: Object.keys(obj).map(k => k + '=' + encodeURIComponent(obj[k])).join('&') – Jannes Apr 21 '15 at 13:34 
2  
Just to note that Object.keys is only available in IE >= 9 – Johnston Jun 2 '15 at 20:26
1  
Further improved @Jannes code using ES6 templates instead of concatenation - Object.keys(obj).map(k => `${k}=${encodeURIComponent(obj[k])}`).join('&') – csilk Jan 25 '17 at 0:16 

Here's a one liner in ES6:

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
shareimprove this answer
 
    
replace key w/ k and you're golden – Jamie Kudla Feb 24 '16 at 17:02
    
edited - thanks @Kudla69 – Nico Tejera Feb 25 '16 at 17:46
6  
Warning! This only works on shallow objects. If you have a top-level property that is another object, this one liner will output "key=%5Bobject%20Object%5D". Just as a heads up. – Andrew Allbright Apr 5 '16 at 18:47
1  
Also, this doesn't spit up arrays. I got export?actions[]=finance,create,edit when it should have export?actions[]=finance&actions[]=create&actions[]=edit as is the awful standard. – darkbluesun Aug 11 '16 at 3:15 
    
Arrays are pretty much always "you're on your own" because URL arguments are just strings as far as the spec is concerned, so you're on the hook to make anything that isn't a single string gets read correctly by the server you're calling. actions[] is PHP notation; Django uses multiple action instead (no [] suffix); some other ORM/CMS require comma-separated lists, etc. So "if it's not simple strings, first make sure you know what your server even wants". – Mike 'Pomax' Kamermans Jan 23 '17 at 19:01 

With Node.js v6.6.3

const querystring = require('querystring')

const obj = {
  foo: 'bar',
  baz: 'tor'
}

let result = querystring.stringify(obj)
// foo=bar&baz=tor

Reference: https://nodejs.org/api/querystring.html

shareimprove this answer
 
4  
This shouldn't be downvoted IMO, if it's JS on the server this should be the correct answer. – Michael BeninAug 11 '16 at 18:11
1  
It seems like it doesn't support nested objects. – Yarin Gold Jan 1 '17 at 13:30
1  
Quote from original question: "No jQuery, no other frameworks - just plain Javascript :)" – Brian Hannay May 10 '17 at 17:05 

A small amendment to the accepted solution by user187291:

serialize = function(obj) {
   var str = [];
   for(var p in obj){
       if (obj.hasOwnProperty(p)) {
           str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
       }
   }
   return str.join("&");
}

Checking for hasOwnProperty on the object makes JSLint/JSHint happy, and it prevents accidentally serializing methods of the object or other stuff if the object is anything but a simple dictionary. See the paragraph on for statements in this page: http://javascript.crockford.com/code.html

shareimprove this answer
 

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() );
shareimprove this answer
 

use JSON.

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

shareimprove this answer
 
2  
I don't know what he's writing the server in, but most modern languages have good packages that read JSON. Besides, even if he ends up implementing it, its better to implement a JSON-reading server code than to invent a new encoding scheme of your own. DIY encodings like this tend to be buggy (because you usually don't think of all the possible cases, like the value being an array in itself etc'). – Ofri Raviv Nov 11 '09 at 13:43
    
are you basically suggesting to convert teh object into JSON and then pass the entire JSON string to the server as a single GET query parameter? – Marco Demaio Nov 13 '12 at 18:24
    
Yes. It seems what OP is asking for. – Ofri Raviv Nov 13 '12 at 19:38
    
not too elegant, but functional; +1 from me. – vaxquis Oct 21 '17 at 16:34

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("&")
shareimprove this answer
 
    
Thanks alfonso! Really saved my time! – Lukas Nov 27 '13 at 15:35

Rails / PHP Style Query Builder

This method converts a Javascript object into a URI Query String. Also handles nested arrays and objects (in Rails / PHP syntax):

function serializeQuery(params, prefix) {
  const query = Object.keys(params).map((key) => {
    const value  = params[key];

    if (params.constructor === Array)
      key = `${prefix}[]`;
    else if (params.constructor === Object)
      key = (prefix ? `${prefix}[${key}]` : key);

    if (typeof value === 'object')
      return serializeQuery(value, key);
    else
      return `${key}=${encodeURIComponent(value)}`;
  });

  return [].concat.apply([], query).join('&');
}

Example Usage:

let params = {
  a: 100,
  b: 'has spaces',
  c: [1, 2, 3],
  d: { x: 9, y: 8}
}

serializeQuery(params)
// returns 'a=100&b=has%20spaces&c[]=1&c[]=2&c[]=3&d[x]=9&d[y]=8
shareimprove this answer
 
    
Nice example. I fixed a typo in your answer. By the way, would be interesting if you edit your function to exclude falsy values (null, undefined, NaN, '')... – developer033 Apr 29 '17 at 22:44

I suggest using the URLSearchParams interface:

const searchParams = new URLSearchParams();
const search = {foo: "hi there", bar: "100%" };
Object.keys(search).forEach(key => searchParams.append(key, search[key]));
console.log(searchParams.toString())
shareimprove this answer
 
    
This should be the accepted answer – rorymorris89 Dec 19 '17 at 13:32

If you want to convert a nested object recursively and the object may or may not contain arrays (and the arrays may contain objects or arrays, etc), then the solution gets a little more complex. This is my attempt.

I've also added some options to choose if you want to record for each object member at what depth in the main object it sits, and to choose if you want to add a label to the members that come from converted arrays.

Ideally you should test if the thing parameter really receives an object or array.

function thingToString(thing,maxDepth,recordLevel,markArrays){
    //thing: object or array to be recursively serialized
    //maxDepth (int or false):
    // (int) how deep to go with converting objects/arrays within objs/arrays
    // (false) no limit to recursive objects/arrays within objects/arrays
    //recordLevel (boolean):
    //  true - insert "(level 1)" before transcript of members at level one (etc)
    //  false - just 
    //markArrays (boolean):
    //  insert text to indicate any members that came from arrays
    var result = "";
    if (maxDepth !== false && typeof maxDepth != 'number') {maxDepth = 3;}
    var runningDepth = 0;//Keeps track how deep we're into recursion

    //First prepare the function, so that it can call itself recursively
    function serializeAnything(thing){
        //Set path-finder values
        runningDepth += 1;
        if(recordLevel){result += "(level " + runningDepth + ")";}

        //First convert any arrays to object so they can be processed
        if (thing instanceof Array){
            var realObj = {};var key;
            if (markArrays) {realObj['type'] = "converted array";}
            for (var i = 0;i < thing.length;i++){
                if (markArrays) {key = "a" + i;} else {key = i;}
                realObj[key] = thing[i];
            }
            thing = realObj;
            console.log('converted one array to ' + typeof realObj);
            console.log(thing);
        }

        //Then deal with it
        for (var member in thing){
            if (typeof thing[member] == 'object' && runningDepth < maxDepth){
                serializeAnything(thing[member]);
                //When a sub-object/array is serialized, it will add one to
                //running depth. But when we continue to this object/array's
                //next sibling, the level must go back up by one
                runningDepth -= 1;
            } else if (maxDepth !== false && runningDepth >= maxDepth) {
                console.log('Reached bottom');
            } else 
            if (
                typeof thing[member] == "string" || 
                typeof thing[member] == 'boolean' ||
                typeof thing[member] == 'number'
            ){
                result += "(" + member + ": " + thing[member] + ") ";
            }  else {
                result += "(" + member + ": [" + typeof thing[member] + " not supported]) ";
            }
        }
    }
    //Actually kick off the serialization
    serializeAnything(thing);

    return result;

}
shareimprove this answer
 
    
Thanks for the recursive approach – Sherlock Aug 11 '15 at 4:49

Here's a concise & recursive version with Object.entries. It handles arbitrarily nested arrays, but not nested objects. It also removes empty elements:

const format = (k,v) => v !== null ? `${k}=${encodeURIComponent(v)}` : ''

const to_qs = (obj) => {
    return [].concat(...Object.entries(obj)
                       .map(([k,v]) => Array.isArray(v) 
                          ? v.map(arr => to_qs({[k]:arr})) 
                          : format(k,v)))
           .filter(x => x)
           .join('&');
}

E.g.:

let json = { 
    a: [1, 2, 3],
    b: [],              // omit b
    c: 1,
    d: "test&encoding", // uriencode
    e: [[4,5],[6,7]],   // flatten this
    f: null,            // omit nulls
    g: 0
};

let qs = to_qs(json)

=> "a=1&a=2&a=3&c=1&d=test%26encoding&e=4&e=5&e=6&e=7&g=0"
shareimprove this answer
 

ok, it's a older post but i'm facing this problem and i have found my personal solution.. maybe can help someone else..

     function objToQueryString(obj){
        var k = Object.keys(obj);
        var s = "";
        for(var i=0;i<k.length;i++) {
            s += k[i] + "=" + encodeURIComponent(obj[k[i]]);
            if (i != k.length -1) s += "&";
        }
        return s;
     };
shareimprove this answer
 

Addition for accepted solution, this works with objects & array of objects:

parseJsonAsQueryString = function (obj, prefix, objName) {
    var str = [];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            var v = obj[p];
            if (typeof v == "object") {
                var k = (objName ? objName + '.' : '') + (prefix ? prefix + "[" + p + "]" : p);
                str.push(parseJsonAsQueryString(v, k));
            } else {
                var k = (objName ? objName + '.' : '') + (prefix ? prefix + '.' + p : p);
                str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
                //str.push(k + "=" + v);
            }
        }
    }
    return str.join("&");
}

Also have added objName if you're using object parameters like in asp.net mvc action methods.

shareimprove this answer
 

A little bit look better

objectToQueryString(obj, prefix) {
    return Object.keys(obj).map(objKey => {
        if (obj.hasOwnProperty(objKey)) {
            const key = prefix ? `${prefix}[${objKey}]` : objKey;
            const value = obj[objKey];

            return typeof value === "object" ?
                this.objectToQueryString(value, key) :
                `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }

        return null;
    }).join("&");
}
shareimprove this answer
 

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('&');
}
shareimprove this answer
 

The above answers fill not work if you have a lot of nested objects. Instead you can pick the function param from here - https://github.com/knowledgecode/jquery-param/blob/master/jquery-param.js It worked very well for me!

    var param = function (a) {
    var s = [], rbracket = /\[\]$/,
        isArray = function (obj) {
            return Object.prototype.toString.call(obj) === '[object Array]';
        }, add = function (k, v) {
            v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
            s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
        }, buildParams = function (prefix, obj) {
            var i, len, key;

            if (prefix) {
                if (isArray(obj)) {
                    for (i = 0, len = obj.length; i < len; i++) {
                        if (rbracket.test(prefix)) {
                            add(prefix, obj[i]);
                        } else {
                            buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]);
                        }
                    }
                } else if (obj && String(obj) === '[object Object]') {
                    for (key in obj) {
                        buildParams(prefix + '[' + key + ']', obj[key]);
                    }
                } else {
                    add(prefix, obj);
                }
            } else if (isArray(obj)) {
                for (i = 0, len = obj.length; i < len; i++) {
                    add(obj[i].name, obj[i].value);
                }
            } else {
                for (key in obj) {
                    buildParams(key, obj[key]);
                }
            }
            return s;
        };

    return buildParams('', a).join('&').replace(/%20/g, '+');
};
shareimprove this answer
 

I have a simpler solution that does not use any third-party library and is already apt to be used in any browser that has "Object.keys" (aka all modern browsers + edge + ie):

In ES5

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

In ES3

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

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 }) );
shareimprove this answer
 
    
Why the negative vote? – Marco Demaio Sep 22 '14 at 18:07

Refer from the answer @user187291, add "isArray" as parameter to make the json nested array to be converted.

data : {
                    staffId : "00000001",
                    Detail : [ {
                        "identityId" : "123456"
                    }, {
                        "identityId" : "654321"
                    } ],

                }

To make the result :

staffId=00000001&Detail[0].identityId=123456&Detail[1].identityId=654321

serialize = function(obj, prefix, isArray) {
        var str = [],p = 0;
        for (p in obj) {
            if (obj.hasOwnProperty(p)) {
                var k, v;
                if (isArray)
                    k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
                else
                    k = prefix ? prefix + "." + p + "" : p, v = obj[p];

                if (v !== null && typeof v === "object") {
                    if (Array.isArray(v)) {
                        serialize(v, k, true);
                    } else {
                        serialize(v, k, false);
                    }
                } else {
                    var query = k + "=" + v;
                    str.push(query);
                }
            }
        }
        return str.join("&");
    };

    serialize(data, "prefix", false);

 

 

https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object

posted @ 2018-01-04 20:19  Focus and Learn  阅读(2674)  评论(0编辑  收藏  举报