本文介紹了JavaScript 對(duì)象 (JSON) 到 URL 字符串格式的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有一個(gè)類似的 JSON 對(duì)象
I've got a JSON object that looks something like
{
"version" : "22",
"who: : "234234234234"
}
我需要將它放在一個(gè)準(zhǔn)備好作為原始 http 正文請(qǐng)求發(fā)送的字符串中.
And I need it in a string ready to be sent as a raw http body request.
所以我需要它看起來像
version=22&who=234324324324
但目前我有無數(shù)個(gè)參數(shù),它需要工作
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 中一定有更好的方法來做到這一點(diǎn)?
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"
原帖
您的解決方案非常好.一個(gè)看起來更好的可能是:
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
這篇關(guān)于JavaScript 對(duì)象 (JSON) 到 URL 字符串格式的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!