Convert JSON array to an HTML table in jQuery

前端 未结 15 882
温柔的废话
温柔的废话 2020-11-22 16:33

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

相关标签:
15条回答
  • 2020-11-22 16:48

    with pure jquery:

    window.jQuery.ajax({
        type: "POST",
        url: ajaxUrl,
        contentType: 'application/json',
        success: function (data) {
    
            var odd_even = false;
            var response = JSON.parse(data);
    
            var head = "<thead class='thead-inverse'><tr>";
            $.each(response[0], function (k, v) {
                head = head + "<th scope='row'>" + k.toString() + "</th>";
            })
            head = head + "</thead></tr>";
            $(table).append(head);//append header
           var body="<tbody><tr>";
            $.each(response, function () {
                body=body+"<tr>";
                $.each(this, function (k, v) {
                    body=body +"<td>"+v.toString()+"</td>";                                        
                }) 
                body=body+"</tr>";               
            })
            body=body +"</tbody>";
            $(table).append(body);//append body
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responsetext);
        }
    });
    
    0 讨论(0)
  • 2020-11-22 16:52

    Make a HTML Table from a JSON array of Objects by extending $ as shown below

    $.makeTable = function (mydata) {
        var table = $('<table border=1>');
        var tblHeader = "<tr>";
        for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
        tblHeader += "</tr>";
        $(tblHeader).appendTo(table);
        $.each(mydata, function (index, value) {
            var TableRow = "<tr>";
            $.each(value, function (key, val) {
                TableRow += "<td>" + val + "</td>";
            });
            TableRow += "</tr>";
            $(table).append(TableRow);
        });
        return ($(table));
    };
    

    and use as follows:

    var mydata = eval(jdata);
    var table = $.makeTable(mydata);
    $(table).appendTo("#TableCont");
    

    where TableCont is some div

    0 讨论(0)
  • 2020-11-22 16:52

    Pivoted single-row view with headers on the left based on @Dr.sai's answer above.

    Injection prevented by jQuery's .text method

    $.makeTable = function (mydata) {
        var table = $('<table>');
        $.each(mydata, function (index, value) {
            // console.log('index '+index+' value '+value);
            $(table).append($('<tr>'));
            $(table).append($('<th>').text(index));
            $(table).append($('<td>').text(value));
        });
        return ($(table));
    };
    
    0 讨论(0)
  • 2020-11-22 16:54

    I found a duplicate over here: Convert json data to a html table

    Well, there are many plugins exists, including commercial one (Make this as commercial project?! Kinda overdone... but you can checkout over here: https://github.com/alfajango/jquery-dynatable)

    This one has more fork: https://github.com/afshinm/Json-to-HTML-Table

    //Example data, Object 
    var objectArray = [{
        "Total": "34",
        "Version": "1.0.4",
        "Office": "New York"
    }, {
        "Total": "67",
        "Version": "1.1.0",
        "Office": "Paris"
    }];
    
    //Example data, Array
    var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"];
    
    //Example data, nested Object. This data will create nested table also.
    var nestedTable = [{
        key1: "val1",
        key2: "val2",
        key3: {
            tableId: "tblIdNested1",
            tableClassName: "clsNested",
            linkText: "Download",
            data: [{
                subkey1: "subval1",
                subkey2: "subval2",
                subkey3: "subval3"
            }]
        }
    }];
    

    Apply the code

    //Only first parameter is required
    var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
    

    Or you might want to checkout this jQuery plugins as well: https://github.com/jongha/jquery-jsontotable

    I think jongha's plugins is easier to use

    <div id="jsontotable" class="jsontotable"></div>
    
    var data = [[1, 2, 3], [1, 2, 3]];
    $.jsontotable(data, { id: '#jsontotable', header: false });
    
    0 讨论(0)
  • 2020-11-22 16:57

    Using jQuery will make this simpler.

    The following code will take an array of arrays and store convert them into rows and cells.

    $.getJSON(url , function(data) {
        var tbl_body = "";
        var odd_even = false;
        $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
                tbl_row += "<td>"+v+"</td>";
            });
            tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
            odd_even = !odd_even;               
        });
        $("#target_table_id tbody").html(tbl_body);
    });
    

    You could add a check for the keys you want to exclude by adding something like

    var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
    

    at the start of the getJSON callback function and adding:

    if ( ( k in expected_keys ) && expected_keys[k] ) {
    ...
    }
    

    around the tbl_row += line.

    Edit: Was assigning a null variable previously

    Edit: Version based on Timmmm's injection-free contribution.

    $.getJSON(url , function(data) {
        var tbl_body = document.createElement("tbody");
        var odd_even = false;
        $.each(data, function() {
            var tbl_row = tbl_body.insertRow();
            tbl_row.className = odd_even ? "odd" : "even";
            $.each(this, function(k , v) {
                var cell = tbl_row.insertCell();
                cell.appendChild(document.createTextNode(v.toString()));
            });        
            odd_even = !odd_even;               
        });
        $("#target_table_id").append(tbl_body);   //DOM table doesn't have .appendChild
    });
    
    0 讨论(0)
  • 2020-11-22 16:59

    You can do this pretty easily with Javascript+Jquery as below. If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!

    //Sample JSON 2D array
    var json = [{
      "Total": "34",
      "Version": "1.0.4",
      "Office": "New York"
    }, {
      "Total": "67",
      "Version": "1.1.0",
      "Office": "Paris"
    }];
    
    // Get Table headers and print
    for (var k = 0; k < Object.keys(json[0]).length; k++) {
      $('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');
    }
    
    // Get table body and print
    for (var i = 0; i < Object.keys(json).length; i++) {
      $('#table_content').append('<tr>');
      for (var j = 0; j < Object.keys(json[0]).length; j++) {
        $('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');
      }
      $('#table_content').append('</tr>');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <thead>
        <tr id="table_head">
    
        </tr>
      </thead>
      <tbody id="table_content">
    
      </tbody>
    </table>

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