20

我有一个看起来像的 JSON 对象

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

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

所以我需要它看起来像

version=22&who=234324324324

但它需要工作,对于无限数量的参数,此刻我有

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

但是,在本机 js 中必须有更好的方法吗?

谢谢

4

1 回答 1

47

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"

原帖

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

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

于 2013-11-11T15:41:00.347 回答