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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19910021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:02:05  来源:igfitidea点击:

JavaScript Object (JSON) to URL String Format

javascriptjsonxmlhttprequestnative

提问by Owen

I've got a JSON object that looks something like

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

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

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

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

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?

但是,在本机 js 中必须有更好的方法来做到这一点吗?

Thanks

谢谢

回答by Tibos

2018 update

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"

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

+1 @Pointy 为 encodeURIComponent