将 URL 转换为 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17483057/
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
Convert URL to json
提问by php_nub_qq
I can't seem to find an answer to this question.. How can I convert a URL parameters string to JSON in javascript? I mean to ask if there is an in-built function like this or a one-liner that could do the job?
我似乎无法找到这个问题的答案.. 如何在 javascript 中将 URL 参数字符串转换为 JSON?我的意思是问是否有这样的内置功能或单线可以完成这项工作?
Example:
例子:
some=params&over=here=> {"some":"params","over":"here"}
some=params&over=here=> {"some":"params","over":"here"}
回答by Satpal
You can create a method which will return JSON object
您可以创建一个返回 JSON 对象的方法
var params = getUrlVars('some=params&over=here');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
// If you want to get in native datatypes
// myJson[hash[0]] = JSON.parse(hash[1]);
}
return myJson;
}
回答by 1nstinct
Try this :
尝试这个 :
var str = 'some1=param&some2=param2';
JSON.parse('{"' + decodeURI(str).replace(/"/g, '\"').replace(/&/g, '","').replace(/=/g,'":"').replace(/\s/g,'') + '"}')
// {some1: "param1", some2: "param2"}
回答by Ray Toal
If it is a one-liner you are after, the Underscore library has a pretty function called object, which takes an array of pairs and builds an object from it:
如果它是你所追求的单行,Underscore 库有一个漂亮的函数叫做object,它接受一组对并从中构建一个对象:
> _.object(["some","param"],["over","here"])
{some: "param", over: "here"}
If you use Underscore, you can one-line the construction of an object from your query string as follows:
如果您使用下划线,您可以从查询字符串中一行一行地构建一个对象,如下所示:
> var s = 'some=param&over=here';
> _.object(s.split('&').map(function(p){return p.split('=');}))
{some: "param", over: "here"}
Now if all you want is the JavaScript object, you are done. You said in your question that you wanted JSON, so the next step is pretty easy:
现在,如果您只需要 JavaScript 对象,就大功告成了。你在你的问题中说你想要JSON,所以下一步很简单:
> JSON.stringify(_.object(s.split('&').map(function(p){return p.split('=');})))
"{\"some\": \"param\", \"over\": \"here\"}"
Here is a live demo
这是一个现场演示
If you are not using Underscore, you can always write a utility function of your own.
如果您不使用 Underscore,您可以随时编写自己的实用程序函数。
This one line is a little ugly, but Firefox 22 has some of the upcoming ES6 features like array comprehensions and arrows, so the code can be made even more compact in the future, e.g.
这一行有点难看,但 Firefox 22 有一些即将推出的 ES6 特性,如数组推导和箭头,因此将来可以使代码更加紧凑,例如
JSON.stringify(_.object(s.split('&').map(p => p.split('='))))
or even
甚至
JSON.stringify(_.object([p.split('=') for (p of s.split('&'))]))
Or maybe just stick to the readable for loops and make your own function. :)
或者也许只是坚持可读的 for 循环并创建自己的函数。:)
回答by CoursesWeb
Try use this function:
尝试使用此功能:
// Returns an object with elements "name: value" with data ftom URL (the "name=value" pairs)
function getDataUrl(url) {
// From: http://coursesweb.net/javascript/
var url_data = url.match(/\?([^#]*)/i)[1]; // gets the string between '?' and '#'
// separate the data into an array, in case the are multiple pairs name=value
var ar_url_data = url_data.split('&');
// traverse the array, and adds into an object elements name:value
var data_url = {};
for(var i=0; i<ar_url_data.length; i++) {
var ar_val = ar_url_data[i].split('='); // separate name and value from each pair
data_url[ar_val[0]] = ar_val[1];
}
return data_url;
}
回答by user326608
I used satpal's answerto provide a nice Razor to JSON pipeline that works with Html.BeginForm, @Html.TextBoxForetc.
我用satpal的答案提供一个很好的剃刀JSON管道与工程Html.BeginForm,@Html.TextBoxFor等等。
The updated getUrlVars function looks like this:
更新后的 getUrlVars 函数如下所示:
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
var value = decodeURIComponent(hash[1]);
value = value.replace("[\"", "");
value = value.replace("\"]", "");
value = value.replace(/\^.*/, "");
myJson[hash[0]] = value;
}
return myJson;
}
The extra replacecalls are for characters I get in my text boxes, probably via the dropdown magicSuggestlookups. The decodeURIComponentcall cleans it up from %'s first.
额外的replace调用是针对我在文本框中得到的字符,可能是通过下拉magicSuggest查找。该decodeURIComponent呼叫首先从 % 清除它。
I call it in a block like this:
我在这样的块中调用它:
var serialized = $("#saveForm").serialize();
var params = getUrlVars(serialized);
The Razor syntax I have looks like this:
我的 Razor 语法如下所示:
@using (Html.BeginForm("SaveNewAddress", "Internal", FormMethod.Post, new { @Id = "saveForm" }))
{
@Html.ValidationSummary()
<table style="width: 100%; margin: 0 auto; padding: 10px">
<tr>
<td colspan="2">
<label>Is this a Liliputian Address?</label>
</td>
<td colspan="4" style="font-size: 1.1em">
<div style="float: left; margin-left: 10px">
<label class="label_check">
@Html.RadioButton("IsLiliputian", "Yes", true, new { @id = "IsLiliputianYes", @style = "width:30px" })
</label>
Yes
</div>
...etc
This provides a nice way to get a bunch of data created in and via ASP.Net MVC controls in a js object that I can throw at a webservice via ajax.
这提供了一种很好的方法来获取在 js 对象中的 ASP.Net MVC 控件中和通过 ASP.Net MVC 控件创建的一堆数据,我可以通过 ajax 将其抛出到 web 服务。

