Trying to parse a JSON file using jQuery

I am trying to parse a JSON file with an exact string, as shown below.

{ "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" } ] } } 

I am using the following jQuery function:

 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('<tr><td><img src="' + img + '" class="picEven pic" width="33" height="35"></td><td><a href="'+ homepage + '" class="networkLink">' + name + '</a></td></tr>'); }); }); } 

Is there something I'm doing wrong?

+4
source share
2 answers

You are not accessing the correct item. data does not point to students , it points to the outermost element {students:...} ( students is its property). The array is contained in data.students.student :

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

Further notes:

  • You do not need to create a local variable if you access the property only once (but, of course, it can be more readable).

  • If consecutive semicolons ;; do not make mistakes, this is not necessary and confusing (at least it bothers me;))

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

Source: https://habr.com/ru/post/1341042/


All Articles