Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert URL to json

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

like image 521
php_nub_qq Avatar asked Jul 05 '13 07:07

php_nub_qq


People also ask

How can I get JSON data from URL?

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 .

What is URL encoded JSON?

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.


2 Answers

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/

like image 172
Satpal Avatar answered Oct 21 '22 08:10

Satpal


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"}
like image 26
1nstinct Avatar answered Oct 21 '22 06:10

1nstinct