Convert JSON array to an HTML table in jQuery

2018-12-31 21:55发布

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?

13条回答
冷夜・残月
2楼-- · 2018-12-31 22:17

Pure HTML way, not vulnerable like the others AFAIK:

// Function to create a table as a child of el.
// data must be an array of arrays (outer array is rows).
function tableCreate(el, data)
{
    var tbl  = document.createElement("table");
    tbl.style.width  = "70%";

    for (var i = 0; i < data.length; ++i)
    {
        var tr = tbl.insertRow();
        for(var j = 0; j < data[i].length; ++j)
        {
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i][j].toString()));
        }
    }
    el.appendChild(tbl);
}

Example usage:

$.post("/whatever", { somedata: "test" }, null, "json")
.done(function(data) {
    rows = [];
    for (var i = 0; i < data.Results.length; ++i)
    {
        cells = [];
        cells.push(data.Results[i].A);
        cells.push(data.Results[i].B);
        rows.push(cells);
    }
    tableCreate($("#results")[0], rows);
});
查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 22:18

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));
};
查看更多
公子世无双
4楼-- · 2018-12-31 22:19

Converting a 2D JavaScript array to an HTML table

To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :

function arrayToTable(tableData) {
    var table = $('<table></table>');
    $(tableData).each(function (i, rowData) {
        var row = $('<tr></tr>');
        $(rowData).each(function (j, cellData) {
            row.append($('<td>'+cellData+'</td>'));
        });
        table.append(row);
    });
    return table;
}

$('body').append(arrayToTable([
    ["John","Slegers",34],
    ["Tom","Stevens",25],
    ["An","Davies",28],
    ["Miet","Hansen",42],
    ["Eli","Morris",18]
]));
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


Loading a JSON file

If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :

$.ajax({
    type: "GET",
    url: "data.json",
    dataType: 'json',
    success: function (data) {
        $('body').append(arrayToTable(data));
    }
});
查看更多
时光乱了年华
5楼-- · 2018-12-31 22:20

I'm not sure if is this that you want but there is jqGrid. It can receive JSON and make a grid.

查看更多
素衣白纱
6楼-- · 2018-12-31 22:24

Using jQuery will make this simpler.

The following 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 cbf 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").appendChild(tbl_body);
});
查看更多
ら面具成の殇う
7楼-- · 2018-12-31 22:24

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);
    }
});
查看更多
登录 后发表回答