JavaScript Object (JSON) to URL String Format

与世无争的帅哥 提交于 2020-01-10 12:38:31

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/19910021/javascript-object-json-to-url-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!