Convert URL to json

前端 未结 6 1272
太阳男子
太阳男子 2020-12-09 04:55

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

6条回答
  •  生来不讨喜
    2020-12-09 05:18

    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/

提交回复
热议问题