Trying to parse JSON file with jQuery

前端 未结 2 604
孤独总比滥情好
孤独总比滥情好 2020-12-17 03:51

I am trying to parse a JSON file with the exact stucture as in the following.

{
    \"students\": {
        \"student\": [
            {
                \"id         


        
相关标签:
2条回答
  • 2020-12-17 04:30
    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>");
        });
    });
    
    0 讨论(0)
  • 2020-12-17 04:40

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

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

    Further notes:

    • You don't need to create a local variable if you access a property only once (but of course it might be more readable).

    • While having consecutive semicolons ;; is not wrong, it is unnecessary and confusing (at least it confuses me ;))

    0 讨论(0)
提交回复
热议问题