json转json树状结构
在写Restful服务的时候,因为都是返回去的都是一条条的json对象,这些都对象之间又是有关系的,但是却没有很好的体现出来,返回到页面的时候,不能成为一个树。返回去的json串数据如下:
[{"belongsname":"","id":901,"isleaf":0,"name":"XJBHX-2标项目部","pid":"","type":""},{"belongsname":"","id":902,"isleaf":1,"name":"综合部(办公室)","pid":"901","type":""},{"belongsname":"","id":903,"isleaf":1,"name":"工程部(工技部/技术部)","pid":"901","type":""},{"belongsname":"","id":904,"isleaf":1,"name":"安质部","pid":"901","type":""},{"belongsname":"","id":905,"isleaf":1,"name":"计财部","pid":"901","type":""},{"belongsname":"","id":906,"isleaf":1,"name":"物设部(物机部)","pid":"901","type":""},{"belongsname":"","id":907,"isleaf":1,"name":"中心试验室","pid":"901","type":""}]
而我们在前台界面上需要的数据可能是这样的:
[
{
"belongsname": "",
"id": 901,
"isleaf": 0,
"name": "XJBHX-2标项目部",
"pid": "",
"type": ""
"children":[ {
"belongsname": "",
"id": 902,
"isleaf": 1,
"name": "综合部(办公室)",
"pid": "901",
"type": ""
},
{
"belongsname": "",
"id": 903,
"isleaf": 1,
"name": "工程部(工技部/技术部)",
"pid": "901",
"type": ""
},
{
"belongsname": "",
"id": 904,
"isleaf": 1,
"name": "安质部",
"pid": "901",
"type": ""
},
{
"belongsname": "",
"id": 905,
"isleaf": 1,
"name": "计财部",
"pid": "901",
"type": ""
},
{
"belongsname": "",
"id": 906,
"isleaf": 1,
"name": "物设部(物机部)",
"pid": "901",
"type": ""
},
{
"belongsname": "",
"id": 907,
"isleaf": 1,
"name": "中心试验室",
"pid": "901",
"type": ""
}]
]
怎么转换呢?看示例:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
//将json串转换成树形结构
function transData(a, idStr, pidStr, chindrenStr) {
var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;
for (; i < len; i++) {
hash[a[i][id]] = a[i];
}
for (; j < len; j++) {
var aVal = a[j], hashVP = hash[aVal[pid]];
if (hashVP) {
!hashVP[children] && (hashVP[children] = []);
hashVP[children].push(aVal);
} else {
r.push(aVal);
}
}
return r;
}
//测试方法
function test() {
//json串
var jsonData = eval('[{"belongsname":"","id":901,"isleaf":0,"name":"XJBHX-2标项目部","pid":"","type":""},{"belongsname":"","id":902,"isleaf":1,"name":"综合部(办公室)","pid":"901","type":""},{"belongsname":"","id":903,"isleaf":1,"name":"工程部(工技部/技术部)","pid":"901","type":""},{"belongsname":"","id":904,"isleaf":1,"name":"安质部","pid":"901","type":""},{"belongsname":"","id":905,"isleaf":1,"name":"计财部","pid":"901","type":""},{"belongsname":"","id":906,"isleaf":1,"name":"物设部(物机部)","pid":"901","type":""},{"belongsname":"","id":907,"isleaf":1,"name":"中心试验室","pid":"901","type":""}]');
//绑定的字段
var jsonDataTree = transData(jsonData, 'id', 'pid', 'chindren');
console.log(jsonDataTree);
}
//窗体加载执行的方法
window.onload = test;
</script>
</head>
</head>
<body>
</body>
</html>
刚开始做的时候,想复杂了,想着自己去遍历然后手动拼写json串,网络永远做着我们先做的事。
更多推荐
所有评论(0)