JavaScript 对象 (JSON) 到 URL 字符串格式

2022-01-15 00:00:00 json native xmlhttprequest javascript

我有一个类似的 JSON 对象

I've got a JSON object that looks something like

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

我需要将它放在一个准备好作为原始 http 正文请求发送的字符串中.

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

所以我需要它看起来像

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);
};

但是在原生 js 中一定有更好的方法来做到这一点?

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

谢谢

推荐答案

2018年更新

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"

原帖

您的解决方案非常好.一个看起来更好的可能是:

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 用于 encodeURIComponent

+1 @Pointy for encodeURIComponent

相关文章