JSON生成树

<!DOCTYPE html>

<html>
<head>
	<title>厕所部门tree</title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	<script>

function myObj(data) {
  var arr = data.split(/\n+/);
  for (var i = 0, len = arr.length; i < len; i++) {
    if (!arr[i]) continue;
    var a = arr[i].split(',');
    var pointer = this;
    for (var j = a.length - 1; j >= 0; j--) {
      var pair = a[j].split('=');
      switch(pair[0]){
        case 'OU':
          pointer[pair[1]] = pointer[pair[1]] || {};
          pointer = pointer[pair[1]];
        break;

        case 'DC':

        break;

        case 'CN':
          if (!pointer['members']) {
            pointer['members'] = [pair[1]];
          } else {
            pointer['members'].push(pair[1]);
          }
        break;

        default:
        
        break;
      }
    }
  }
}

function createTree(json){
	function travel(obj){  //遍历传入的obj
		html = html || [], stack = stack || [];
		html.push('<ul>');
		stack.push('</ul>');
		for (var key in obj) {
			html.push('<li>');
			stack.push('</li>');
			var t = Object.prototype.toString.call(obj[key]);
			if (t == '[object Object]') {
				html.push(key);
				arguments.callee(obj[key]);
			} else if(t == '[object Array]'){
				html.push(obj[key].join('</li><li>'));
			}
			html.push(stack.pop());
		}
		html.push(stack.pop());
	}
	var html = [], stack = [];
	travel(json);
	return html.join('');
}
function $(id){
	return document.getElementById(id);
}

function btnCreateTree_click(){
	var data = $('data').value, json = new myObj(data), html = createTree(json);
	$('tree').innerHTML = html;
	$('innerHTML').innerHTML = html.replace(/>/g, '&gt;').replace(/</g, '&lt;');
}

window.onload = function(){
	$('data').value = '\
CN=李三江,OU=数据管理部,OU=西瓜果业销售部\n\
\n\
CN=李四江,OU=数据管理部,OU=西瓜果业销售部\n\
\n\
CN=李五江,OU=数据管理部,OU=西瓜果业销售部\n\
\n\
CN=李⑥江,OU=数据管理部,OU=西瓜果业销售部\n\
\n\
CN=李⑦江,OU=数据管理部,OU=西瓜果业销售部\n\
\n\
CN=蒋黄河,OU=数据管理部,OU=葡萄果业销售部\n\
\n\
CN=李刚,OU=数据管理部,OU=葡萄果业销售部\n\
\n\
CN=李双江,OU=数据管理部,OU=葡萄果业销售部\n\
\n\
CN=李H志,OU=数据管理部,OU=葡萄果业销售部\n\
\n\
CN=Jiang,OU=坑爹管理部,OU=葡萄果业销售部\n\
\n\
CN=毛,OU=数据管理部,OU=葡萄果业销售部\n\
\n\
CN=李牛人,OU=扫厕所部,OU=传销部\n\
';
	$('btnCreateTree').onclick = btnCreateTree_click;
	btnCreateTree_click();
}
	</script>
	<style>
	#tree { width:48%; float:left; }
	#html { width:48%; float:left; }
	</style>
</head>

<body>
  <div id="dataWrap">
    DATA:<br />
    <textarea id="data" rows="10" cols="50"></textarea>
  </div>
  <input type="button" id="btnCreateTree" value="Create Tree↓">
  <div>
    <div id="tree"></div>
    <div id="html" style="width:30%">
      innerHTML:<br />
      <div id="innerHTML"></div>
    </div>
  </div>
</body>
</html>
posted @ 2011-10-14 15:09  Arliang  阅读(4777)  评论(0编辑  收藏  举报