日期:2014-05-16  浏览次数:20361 次

json 解析
有json如下:
{id:'top_1',pId:'',name:'山西省'}
{id:'top_2',pId:'',name:'河北省'}
{id:'top_3',pId:'',name:'辽宁省'}
{id:'top_11',pId:'top_1',name:'太原市'}
{id:'top_12',pId:'top_1',name:'大同市'}
{id:'top_13',pId:'top_1',name:'阳泉市'}
{id:'top_21',pId:'top_2',name:'石家庄市'}
{id:'top_22',pId:'top_2',name:'保定市'}
{id:'top_31',pId:'top_3',name:'沈阳市'}
……

期望格式:

---山西省
  ---太原市
  ---大同市
  ---阳泉市
---河北省
  ---石家庄市
  ---保定市
---辽宁省
  ---沈阳市

如何生成如此结构的html?

------解决方案--------------------
<script type="text/javascript">
var json = [
{id:'top_1',pId:'',name:'山西省'},
{id:'top_2',pId:'',name:'河北省'},
{id:'top_3',pId:'',name:'辽宁省'},
{id:'top_11',pId:'top_1',name:'太原市'},
{id:'top_12',pId:'top_1',name:'大同市'},
{id:'top_13',pId:'top_1',name:'阳泉市'},
{id:'top_21',pId:'top_2',name:'石家庄市'},
{id:'top_22',pId:'top_2',name:'保定市'},
{id:'top_31',pId:'top_3',name:'沈阳市'},
];
for(var x in json){
var tmp = json[x];
if( tmp.pId == '' ){
document.write( tmp.name + '<br />' );
for( var y in json ){
var t = json[y];
if( t.pId == tmp.id ){
document.write( '&emsp;' + t.name + '<br />' );
}
}
}
}
</script>


参考下
------解决方案--------------------
是这样?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>修改对象原型</title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
var json = [{ id: 'top_1', pId: '', name: '山西省' }, { id: 'top_2', pId: '', name: '河北省' }, { id: 'top_11', pId: 'top_1', name: '太原市' }, { id: 'top_12', pId: 'top_1', name: '大同市' }, { id: 'top_21', pId: 'top_2', name: '石家庄市' }, { id: 'top_22', pId: 'top_2', name: '保定市'}];
for (var data1 in json) {
if (json[data1].pId == '') {
document.writeln(json[data1].name + "<br/>");
for (var data2 in json) {
if (json[data2].pId == json[data1].id) {
document.writeln("--"+json[data2].name+"<br/>");
}
}
}
}
</script>
 </head>
 <body>

 </body>
</html>