简体   繁体   中英

JavaScript Object (JSON) to URL String Format

I've got a JSON object that looks something like

{
    "version" : "22",
    "who: : "234234234234"
}

And I need it in a string ready to be sent as a raw http body request.

So i need it to look like

version=22&who=234324324324

But It needs to work, for an infinite number of paramaters, at the moment I've got

app.jsonToRaw = function(object) {
    var str = "";
    for (var index in object) str = str + index + "=" + object[index] + "&";
    return str.substring(0, str.length - 1);
};

However there must be a better way of doing this in native js?

Thanks

2018 update

 var obj = { "version" : "22", "who" : "234234234234" }; const queryString = Object.entries(obj).map(([key, value]) => { return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; }).join('&'); console.log(queryString); // "version=22&who=234234234234" 

Original post

Your solution is pretty good. One that looks better could be:

var obj = {
    "version" : "22",
    "who" : "234234234234"
};

var str = Object.keys(obj).map(function(key){ 
  return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]); 
}).join('&');

console.log(str); //"version=22&who=234234234234"

+1 @Pointy for encodeURIComponent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM