JavaScript 对象 (JSON) 到 URL 字符串格式 [英] JavaScript Object (JSON) to URL String Format

查看:34
本文介绍了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 字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆