1

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?

3

3 Answers 3

5

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.