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"}
Get JSON From URL Using jQuerygetJSON(url, data, success) is the signature method for getting JSON from an URL. In this case, the URL is a string that ensures the exact location of data, and data is just an object sent to the server. And if the request gets succeeded, the status comes through the success .
Json url-encoder tool What is a json url-encoder? This tool converts JavaScript Object Notation (JSON) data to URL-encoding. All special URL characters get escaped to percent-number-number format. Json url-encoder examples Click to use. URL-escape a JSON Array.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With