JavaScript Object (JSON) to URL String Format(JavaScript 对象 (JSON) 到 URL 字符串格式)
问题描述
我有一个类似的 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
这篇关于JavaScript 对象 (JSON) 到 URL 字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 对象 (JSON) 到 URL 字符串格式


基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01