www.zhihu.com/question/25147806/answer/30178499
- 代码如下:JSON:test.json{
"programmers": [
{
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
},
{
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
},
{
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
}
],
"authors": [
{
"firstName": "Isaac",
"lastName": "Asimov",
"genre": "science fiction"
},
{
"firstName": "Tad",
"lastName": "Williams",
"genre": "fantasy"
},
{
"firstName": "Frank",
"lastName": "Peretti",
"genre": "christian fiction"
}
],
"musicians": [
{
"firstName": "Eric",
"lastName": "Clapton",
"instrument": "guitar"
},
{
"firstName": "Sergei",
"lastName": "Rachmaninoff",
"instrument": "piano"
}
]
}
### HTML: test.html<!Doctype html>
```<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
table{ border-collapse:collapse;
color:#333;
border:1px solid #333;
}
td,th{
line-height:1.5em;
padding:3px 5px;
text-align:left;
border:1px solid #333;
}
th{
font-size:1.3em;
line-height:1.8em;
color:#f00;
}
.tit{
font-weight:bold;
}
</style>
</head>
<body>
<button id="btn">加载</button>
<br />
<br />
<table id="test" border="1" width="800">
</table>
<script type="text/javascript">
$("#btn").click(function(){
var html="";
$.getJSON("test.json",function(data){
$.each(data,function(Name,db){
html+="<tr><th colspan='6'>"+Name+"</th></tr>";
var jsonarray =db;
for(var i =0;i<jsonarray.length;i++){
var jsonobj = jsonarray[i];
html+="<tr>";
for(var x in jsonobj){
html+="<td class='tit'>"+x+"</td><td>"+jsonobj[x]+"</td>"
}
html+="</tr>";
}
})
$("#test").html(html);
})
})
</script>
</body>
</html>