简体   繁体   中英

String URL to json object

I was trying to make a JSON Object from a String URL without success

i have this:

var URL = "http://localhost/index.php?module=search&param1=4";

i need this:

var dir = index.php;
var result = {
           module:'search',
           param1:4
             };

Can anyone help me with the code?

It's not entirely correct to post a link here, but in this case what OP needed is just some library to parse urls.

And here it is: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

This function can parse variables AND arrays from a string URL:

function url2json(url) {
   var obj={};

   function arr_vals(arr){
      if (arr.indexOf(',') > 1){
         var vals = arr.slice(1, -1).split(',');
         var arr = [];
         for (var i = 0; i < vals.length; i++)
            arr[i]=vals[i];
         return arr;
      }
      else
         return arr.slice(1, -1);
   }

   function eval_var(avar){
      if (avar[1].indexOf('[') == 0)
         obj[avar[0]] = arr_vals(avar[1]);
      else
         obj[avar[0]] = avar[1];
   }

   if (url.indexOf('?') > -1){
      var params = url.split('?')[1];
      if(params.indexOf('&') > 2){
         var vars = params.split('&');
         for (var i in vars)
            eval_var(vars[i].split('='));
      }
      else
         eval_var(params.split('='));
   }

   return obj;
}

In your case:

obj = url2json("http://localhost/index.php?module=search&param1=4");
console.log(obj.module);
console.log(obj.param1);

Gives:

"search"
"4"

If you want to convert "4" to an integer you have to do it manually.

This simple javascript does it

url = "http://localhost/index.php?module=search&param1=4";
var parameters = url.split("?");
var string_to_be_parsed = parameters[1];

var param_pair_string = string_to_be_parsed.split("&");
alert(param_pair_string.length);
var i = 0;
var json_string = "{"

for(;i<param_pair_string.length;i++){
var pair = param_pair_string[i].split("=");
if(i < param_pair_string.length - 1 )
 json_string +=  pair[0] + ":'" + pair[1] + "',";
else
 json_string +=  pair[0] + ":'" + pair[1] + "'";
}

json_string += "}";
alert(json_string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM