How to append json array data to html table tbody

后端 未结 3 1061
迷失自我
迷失自我 2021-01-24 03:21

I am very new into jQuery and JSON. I need to parse a JSON of the following format so as to populate a html table tbody:

{\"response\":[[\"name0\",\"id0\",\"amt0         


        
相关标签:
3条回答
  • 2021-01-24 03:31

    Not tested but it can be something like:

    var jsondata=$.parseJSON('{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}');
    
    $.each(jsondata.response, function(i, d) {
       var row='<tr>';
       $.each(d, function(j, e) {
          row+='<td>'+e+'</td>';
       });
       row+='</tr>';
       $('#table tbody').append(row);
    });
    
    0 讨论(0)
  • 2021-01-24 03:47

    You can access the JSON structure wiht this Javascript expression:

    var matrix = {"response":[["name0","id0","amt0"],["name1","id1","amt1"]]};
    

    The j-th column of the i-th element is accessible with this:

    matrix.response[i][j]
    
    0 讨论(0)
  • 2021-01-24 03:48

    Call jsonToHtmlTable(jsonObj, '#records'); after following HTML (e.g in document ready)

    Html

    <table id="records">
        <thead>
            <tr></tr>
        </thead>
        <tbody></tbody>
    </table>
    

    JavaScript

    //Sample JSON Object (array of json objects)
    var jsonObj = [{"a":1,"b":3,"ds":4},{"a":2,"b":5,"ds":4}];
    
    //Use
    $(document).ready(function(){
         jsonToHtmlTable(jsonObj, '#records');
    });
    
    //implementation
    function jsonToHtmlTable(jsonObj, selector) {
        addColumns(jsonObj, selector);
        addRows(jsonObj, selector);
    }
    
    function addColumns(jsonObj, selector) {
        if (!$.isArray(jsonObj) || jsonObj.length < 1)
            return;
        var object = jsonObj[0];
        var theadHtml = "";
        for (var property in object) {
            if (object.hasOwnProperty(property))
                theadHtml += "<th>" + property + "</th>";
        }
        $(selector + ' thead tr').html(theadHtml);
    }
    
    function addRows(jsonObj, selector) {
        var tbody = $(selector + ' tbody');
        $.each(jsonObj, function (i, d) {
            var row = '<tr>';
            $.each(d, function (j, e) {
                row += '<td>' + e + '</td>';
            });
            row += '</tr>';
            tbody.append(row);
        });
    }
    
    0 讨论(0)
提交回复
热议问题