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¶m1=4";
i need this:
var dir = index.php;
var result = {
module:'search',
param1:4
};
Can anyone help me with the code?
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¶m1=4";
i need this:
var dir = index.php;
var result = {
module:'search',
param1:4
};
Can anyone help me with the code?
Share Improve this question asked Sep 18, 2012 at 2:04 Damian SIlveraDamian SIlvera 8661 gold badge9 silver badges19 bronze badges 3- 2 james.padolsey./javascript/parsing-urls-with-the-dom – zerkms Commented Sep 18, 2012 at 2:06
- There's also a jQuery (not really) version: github./allmarkedup/jQuery-URL-Parser – Blender Commented Sep 18, 2012 at 2:07
- @zerkms that works great and was just what i needed, post the answer if you want me to accept it. thanks!! – Damian SIlvera Commented Sep 18, 2012 at 2:10
3 Answers
Reset to default 5It'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./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¶m1=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¶m1=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);