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?
Example:
some=params&over=here
=> {"some":"params","over":"here"}
Try this :
Try use this function:
I used satpal's answer to provide a nice Razor to JSON pipeline that works with
Html.BeginForm
,@Html.TextBoxFor
etc.The updated getUrlVars function looks like this:
The extra
replace
calls are for characters I get in my text boxes, probably via the dropdownmagicSuggest
lookups. ThedecodeURIComponent
call cleans it up from %'s first.I call it in a block like this:
The Razor syntax I have looks like this:
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.
You can create a method which will return JSON object
Demo: http://jsfiddle.net/jAGN5/
You might want to try something like
I got this from here
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:If you use Underscore, you can one-line the construction of an object from your query string as follows:
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:
Here is a live demo
If you are not using Underscore, you can always write a utility function of your own.
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.
or even
Or maybe just stick to the readable for loops and make your own function. :)