Javascript 将查询字符串反序列化为 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11557526/
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
Deserialize query string to JSON object
提问by BreakPhreak
Tried to find how to make {foo:"bar"}
from ?...&foo=bar&...
but googled and got only to jQuery.params
which does the opposite. Any suggestions please (built-in javascript function, jquery, underscore.js- all goes)? Or, do I need to implement it by myself (not a big hassle, just trying not to reinvent the wheel)?
试图找到如何制作{foo:"bar"}
,?...&foo=bar&...
但在谷歌上搜索并得到jQuery.params
了相反的结果。请提出任何建议(内置 javascript 函数、jquery、underscore.js- 一切顺利)?或者,我是否需要自己实现它(不是一个大麻烦,只是尽量不要重新发明轮子)?
采纳答案by Zagor23
You have Ben Alman's jQuery BBQ
and a jQuery.deparam
in it. It is described as The opposite of jQuery.param, pretty much.
你有本阿尔曼的jQuery BBQ
和一个jQuery.deparam
。它被描述为The opposite of jQuery.param, pretty much.
http://benalman.com/code/projects/jquery-bbq/examples/deparam/
http://benalman.com/code/projects/jquery-bbq/examples/deparam/
First example is exactly what you need.
第一个示例正是您所需要的。
回答by Carlo G
Actually the above answer by @talsibony doesn't take into account query string arrays (such as test=1&test=2&test=3&check=wow&such=doge
). This is my implementation:
实际上@talsibony 的上述答案没有考虑查询字符串数组(例如test=1&test=2&test=3&check=wow&such=doge
)。这是我的实现:
function queryStringToJSON(qs) {
qs = qs || location.search.slice(1);
var pairs = qs.split('&');
var result = {};
pairs.forEach(function(p) {
var pair = p.split('=');
var key = pair[0];
var value = decodeURIComponent(pair[1] || '');
if( result[key] ) {
if( Object.prototype.toString.call( result[key] ) === '[object Array]' ) {
result[key].push( value );
} else {
result[key] = [ result[key], value ];
}
} else {
result[key] = value;
}
});
return JSON.parse(JSON.stringify(result));
};
回答by talsibony
I am posting here my function just in case other will look and will want to get it straight forward no need for jquery native JS. Because I was looking for the same thing and finally made this function after viewing others answers:
我在这里发布我的函数,以防其他人会查看并希望直接使用它,不需要 jquery 本机 JS。因为我一直在找同样的东西,最后看了别人的回答后做了这个功能:
function queryStringToJSON(queryString) {
if(queryString.indexOf('?') > -1){
queryString = queryString.split('?')[1];
}
var pairs = queryString.split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return result;
}
console.log(queryStringToJSON(window.location.href));
console.log(queryStringToJSON('test=1&check=wow'));//Object {test: "1", check: "wow"}
回答by lfender6445
for simple and flat query strings, something like this will do the trick
对于简单而扁平的查询字符串,像这样的事情就可以解决问题
const queryStringToObject = (queryString) => {
let obj = {}
if(queryString) {
queryString.slice(1).split('&').map((item) => {
const [ k, v ] = item.split('=')
v ? obj[k] = v : null
})
}
return obj
}
> queryStringToObject('?foo=bar&baz=buzz')
{ foo: 'bar', baz: 'buzz' }
回答by Penny Liu
In modern browsers, you can also use Object.fromEntrieswhich makes this even easier.
在现代浏览器中,您还可以使用Object.fromEntries使这更容易。
function queryStringToObject(queryString) {
const pairs = queryString.substring(1).split('&');
// → ["foo=bar", "baz=buzz"]
var array = pairs.map((el) => {
const parts = el.split('=');
return parts;
});
// → [["foo", "bar"], ["baz", "buzz"]]
return Object.fromEntries(array);
// → { "foo": "bar", "baz": "buzz" }
}
console.log(queryStringToObject('?foo=bar&baz=buzz'));
For your case, it would be:
对于您的情况,它将是:
console.log(
Object.fromEntries(new URLSearchParams('foo=bar&baz=buzz'))
);