试图用jQuery解析JSON文件

我试图解析具有精确结构的JSON文件,如下所示。

{ "students": { "student": [ { "id": 1, "name": "John Doe", "image": "pic1.jpg", "homepage": "http: //www.google.com" }, { "id": 2, "name": "Jane Doe", "image": "pic1.jpg", "homepage": "http: //www.google.com" } ] } } 

我使用以下jQuery函数:

 function GetStudents(filename) { $.getJSON(filename, function(data){ $.each(data.student, function(i,s){ var id = s.id;; var name = s.name;; var img = s.image;; var homepage = s.homepage; $('.networkTable').append('' + name + ''); }); }); } 

有什么我做错了吗?

您没有访问正确的元素。 data并不指向students ,它指向最外层的元素{students:...}students是其中的一个属性)。 该数组包含在data.students.student

 $.each(data.students.student, function() { //... }); 

附加说明:

  • 如果只访问一次属性,则不需要创建局部变量(当然它可能更具可读性)。

  • 连续分号时;; 没有错,这是不必要的和令人困惑的(至少它让我困惑;))

 s.nametry: 
$("document").ready(function() { $.getJSON(fileUrl, function(data) { $("#div-my-table").text("<table>"); $.each(data, function(i, item) { $("#div-my-table").append("<tr><td>" + item.prop1 +"</td><td>" + item.prop2 + "</td></tr>"); }); $("#div-my-table").append("</table>"); }); });