Convert URL to json Convert URL to json json json

Convert URL to json


You can create a method which will return JSON object

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;}

Demo: http://jsfiddle.net/jAGN5/


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"}


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:

> _.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:

> 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.

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.

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. :)