最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - String URL to json object - Stack Overflow

programmeradmin1浏览0评论

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?

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?

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
Add a ment  | 

3 Answers 3

Reset to default 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./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);
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>