Javascript 是否有任何本机函数将 json 转换为 url 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14525178/
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
Is there any native function to convert json to url parameters?
提问by Felipe Morales
I need convert json object to url form like: "parameter=12&asd=1"
我需要将 json 对象转换为 url 形式,如:“parameter=12&asd=1”
I done with this:
我完成了这个:
var data = {
'action':'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2' : 3
};
var string_=JSON.stringify(data);
string_=string_.replace(/{/g, "");
string_=string_.replace(/}/g, "");
string_=string_.replace(/:/g, "=")
string_=string_.replace(/,/g, "&");
string_=string_.replace(/"/g, "");
But i wonder if there any function in javascript or in JSON object to do this?
但我想知道 javascript 或 JSON 对象中是否有任何函数可以做到这一点?
回答by georg
jQuery provides paramthat does exactly that. If you don't use jquery, take at look at the source.
jQuery 提供的param正是这样做的。如果您不使用 jquery,请查看源代码。
Basically, it goes like this:
基本上,它是这样的:
url = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&')
2019 update: there's now a built-in object URLSearchParamsfor this type of thing:
2019 年更新:现在有一个URLSearchParams用于此类事物的内置对象:
let myParams = {'foo': 'hi there', 'bar': '???'};
let u = new URLSearchParams(myParams).toString();
console.log(u);
回答by Tareq
Using ES6 syntax:
使用 ES6 语法:
var data = {
'action':'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2' : 3
};
let urlParameters = Object.entries(data).map(e => e.join('=')).join('&');
console.log(urlParameters);
回答by Cezar D.
Something I find nicely looking in ES6:
我在 ES6 中发现很好看的东西:
function urlfy(obj) {
return Object
.keys(obj)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
.join('&');
}
Later update (same thing, maybe a bit cleaner):
稍后更新(同样的事情,也许更干净一点):
const urlfy = obj => Object
.keys(obj)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]))
.join('&');
回答by Minko Gechev
You don't need to serialize this object literal.
您不需要序列化此对象文字。
Better approach is something like:
更好的方法是这样的:
function getAsUriParameters(data) {
var url = '';
for (var prop in data) {
url += encodeURIComponent(prop) + '=' +
encodeURIComponent(data[prop]) + '&';
}
return url.substring(0, url.length - 1)
}
getAsUriParameters(data); //"action=actualiza_resultado&postID=1&gl=2&gl2=3"
回答by Quentin
But i wonder if there any function in javascript
但我想知道javascript中是否有任何功能
Nothing prewritten in the core.
内核中没有任何预先写入的内容。
or json to do this?
或 json 来做到这一点?
JSON is a data format. It doesn't have functions at all.
JSON 是一种数据格式。它根本没有功能。
This is a relatively trivial problem to solve though, at least for flat data structures.
不过,这是一个相对微不足道的问题,至少对于平面数据结构而言是这样。
Don't encode the objects as JSON, then:
不要将对象编码为 JSON,然后:
function obj_to_query(obj) {
var parts = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return "?" + parts.join('&');
}
alert(obj_to_query({
'action': 'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2': 3
}));
There isn't a standard way to encode complex data structures (e.g. with nested objects or arrays). It wouldn't be difficult to extend this to emulate the PHP method (of having square brackets in field names) or similar though.
没有标准的方法来编码复杂的数据结构(例如,使用嵌套对象或数组)。扩展它以模拟 PHP 方法(在字段名称中包含方括号)或类似方法并不困难。
回答by Guilherme
Like @georg said, you can use JQuery.paramfor flat objects.
就像@georg 所说的那样,您可以将JQuery.param用于平面对象。
If you need to process complex objects, you can use JsonUri, a python package that does just that. There is JavaScript library for it as well
如果您需要处理复杂的对象,您可以使用JsonUri,这是一个可以做到这一点的 Python 包。它也有 JavaScript 库
Disclaimer: I am the author of JSONURI
免责声明:我是 JSONURI 的作者
Edit: I learned much later that you can also just base64 encode your payload - most languages as support for base64 encoding/decoding
编辑:我后来了解到你也可以只对你的负载进行 base64 编码 - 大多数语言都支持 base64 编码/解码
Example
例子
x = {name: 'Petter', age: 47, places: ['Mozambique', 'Zimbabwe']}
stringRep = JSON.stringify(x)
encoded = window.btoa(stringRep)
Gives you eyJuYW1lIjoiUGV0dGVyIiwiYWdlIjo0NywicGxhY2VzIjpbIk1vemFtYmlxdWUiLCJaaW1iYWJ3ZSJdfQ==, which you can use as a uri parameter
为您提供eyJuYW1lIjoiUGV0dGVyIiwiYWdlIjo0NywicGxhY2VzIjpbIk1vemFtYmlxdWUiLCJaaW1iYWJ3ZSJdfQ==,您可以将其用作 uri 参数
decoded = window.atob(encoded)
originalX = JSON.parse(decoded)
Needless to say, it comes with its own caveats
不用说,它有自己的警告
回答by ishidex2
I made an implementation that support nested objects and arrays i.e.
我做了一个支持嵌套对象和数组的实现,即
var data = {
users: [
{
"name": "jeff",
"tasks": [
"Do one thing",
"Do second thing"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
Will be:
将会:
users[0][name]=jeff&users[0][tasks][0]=Do%20one%20thing&users[0][tasks][1]=Do%20second%20thing&users[1][name]=rick&users[1][tasks][0]=Never%20gonna%20give%20you%20up&users[1][tasks][1]=Never%20gonna%20let%20you%20down
So, here's the implementation:
所以,这是实现:
var isObj = function(a) {
if ((!!a) && (a.constructor === Object)) {
return true;
}
return false;
};
var _st = function(z, g) {
return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
};
var fromObject = function(params, skipobjects, prefix) {
if (skipobjects === void 0) {
skipobjects = false;
}
if (prefix === void 0) {
prefix = "";
}
var result = "";
if (typeof(params) != "object") {
return prefix + "=" + encodeURIComponent(params) + "&";
}
for (var param in params) {
var c = "" + prefix + _st(param, prefix);
if (isObj(params[param]) && !skipobjects) {
result += fromObject(params[param], false, "" + c);
} else if (Array.isArray(params[param]) && !skipobjects) {
params[param].forEach(function(item, ind) {
result += fromObject(item, false, c + "[" + ind + "]");
});
} else {
result += c + "=" + encodeURIComponent(params[param]) + "&";
}
}
return result;
};
var data = {
users: [{
"name": "jeff",
"tasks": [
"Do one thing",
"Do second thing"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
document.write(fromObject(data));
回答by Perki
This one processes arrays with by changing the nameinto mutiple name[]
这一个通过改变name成多个来处理数组name[]
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
回答by abelabbesnabi
Best solution for Vanilla JavaScript:
Vanilla JavaScript 的最佳解决方案:
var params = Object.keys(data)
.filter(function (key) {
return data[key] ? true : false
})
.map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
})
.join('&');
PS: The filter is used here to remove null or undefined parameters. It makes the url look cleaner.
PS:这里使用过滤器去除空或未定义的参数。它使网址看起来更干净。
回答by josh123a123
The custom code above only handles flat data. And JQuery is not available in react native. So here is a js solution that does work with multi-level objects and arrays in react native.
上面的自定义代码只处理平面数据。并且 JQuery 在 react native 中不可用。所以这里有一个 js 解决方案,它可以在 react native 中处理多级对象和数组。
function formurlencoded(data) {
const opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let sorted = Boolean(opts.sorted),
skipIndex = Boolean(opts.skipIndex),
ignorenull = Boolean(opts.ignorenull),
encode = function encode(value) {
return String(value).replace(/(?:[##代码##-\x1F"-&\+-\}\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g, encodeURIComponent).replace(/ /g, '+').replace(/[!'()~\*]/g, function (ch) {
return '%' + ch.charCodeAt().toString(16).slice(-2).toUpperCase();
});
},
keys = function keys(obj) {
const keyarr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Object.keys(obj);
return sorted ? keyarr.sort() : keyarr;
},
filterjoin = function filterjoin(arr) {
return arr.filter(function (e) {
return e;
}).join('&');
},
objnest = function objnest(name, obj) {
return filterjoin(keys(obj).map(function (key) {
return nest(name + '[' + key + ']', obj[key]);
}));
},
arrnest = function arrnest(name, arr) {
return arr.length ? filterjoin(arr.map(function (elem, index) {
return skipIndex ? nest(name + '[]', elem) : nest(name + '[' + index + ']', elem);
})) : encode(name + '[]');
},
nest = function nest(name, value) {
const type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : typeof value === 'undefined' ? 'undefined' : typeof(value);
let f = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
if (value === f) f = ignorenull ? f : encode(name) + '=' + f; else if (/string|number|boolean/.test(type)) f = encode(name) + '=' + encode(value); else if (Array.isArray(value)) f = arrnest(name, value); else if (type === 'object') f = objnest(name, value);
return f;
};
return data && filterjoin(keys(data).map(function (key) {
return nest(key, data[key]);
}));
}
}

